You may use the Clump tool in the open-source geospatial data analysis platform WhiteboxTools. This can be scripted in Python as follows:
from WBT.whitebox_tools import WhiteboxTools
wbt = WhiteboxTools()
wbt.work_dir = "/path/to/data/"
in_file = "input_raster.tif"
out_file = "output_raster.tif"
wbt.clump(in_file, out_file, diag=True, zero_back=False)
See the WhiteboxTools User Manual for more information on operation or the WhiteboxTools Python Tutorial. For the tool's source code, see here. The WhiteboxTools binary executable (~8 MB) can be downloaded from the Geomorphometry and Hydrogeomatics Research Group page.
The Clump tool re-categorizes data in a raster image by grouping cells that form physically discrete, connected areas into unique categories. Essentially this will produce a patch map from an input categorical image. The input image should either be Boolean (1's and 0's) or categorical. The 'diag' flag is used to include/exclude diagonal neighbour connections. Set the 'zero_back' flag to True if you would like to only assign contiguous groups of non-zero values in the input image unique identifiers.
If you would prefer to call the tool directly from the command line (no Python), then you can do so by first changing the directory (cd'ing) to the WhiteboxTools folder, and using the following command:
./whitebox_tools -r=Clump -v --wd="/path/to/data/" -i=input.tif -o=output.tif --diag
If you're on Windows, the executable will be named whitebox_tools.exe instead. There is a tutorial on how to run WhiteboxTools from the command line here.