Search code examples
pythonopencvcolorsdrawing

Python OpenCV: Why does fillPoly() only draw grey polygons, regardless of its color argument?


I am trying to write a white mask on a black, two-dimensional NumPy array — an image with one channel — in OpenCV using Python:

mask = np.zeros(shape=(100, 100), dtype=np.int8)
cv2.fillPoly(mask, np.array([[[0,0], [89, 0], [99,50], [33,96], [0,47]]], dtype=np.int32), color=255)
print(mask)

However, the polygon has a grey color when I print the mask:

[[127 127 127 ...   0   0   0]
 [127 127 127 ...   0   0   0]
 [127 127 127 ...   0   0   0]
 ...
 [  0   0   0 ...   0   0   0]
 [  0   0   0 ...   0   0   0]
 [  0   0   0 ...   0   0   0]]

I tried a 3D NumPy array with color=(255,255,255), I tried different colours, all to no avail. Why is it ignoring the color argument?


Solution

  • The problem comes from the initialization of your mask:

    mask = np.zeros(shape=(100, 100), dtype=np.int8)
    

    The value range of the int8 data type is -128 ... 127, thus any value above 127 will be "truncated" to 127.

    Try your code with color=100, you'll get the expected output:

    [[100 100 100 ...   0   0   0]
     [100 100 100 ...   0   0   0]
     [100 100 100 ...   0   0   0]
     ...
     [  0   0   0 ...   0   0   0]
     [  0   0   0 ...   0   0   0]
     [  0   0   0 ...   0   0   0]]
    

    I guess, you wanted to use uint8 instead of int8, so maybe it's just a simple typo!?

    Changing your code accordingly to

    mask = np.zeros(shape=(100, 100), dtype=np.uint8)
    

    then gives the expected result, also for color=255:

    [[255 255 255 ...   0   0   0]
     [255 255 255 ...   0   0   0]
     [255 255 255 ...   0   0   0]
     ...
     [  0   0   0 ...   0   0   0]
     [  0   0   0 ...   0   0   0]
     [  0   0   0 ...   0   0   0]]