Home > Mobile >  Why is cv2.COLOR_RGB2GRAY failing with Unsupported depth of input image?
Why is cv2.COLOR_RGB2GRAY failing with Unsupported depth of input image?

Time:05-08

I have a mask that is generated from an ML program which is (544,544,1). RGB image is (544,544,3). I need to find the contours in the mask and draw them on RGB image. I was trying to convert the mask into grayscale but all attempts failed likely due to format issues.

resized_image - Incomming RGB image
mask - Mask generated from ML script

print(f"Resized rgb image shape : {resized_image.shape}, Mask image shape {mask.shape}")
tmp_mask = np.zeros(resized_image.shape, dtype=np.uint8) 255 
bump = tmp_mask * mask
print(bump.shape)
gray = cv2.cvtColor(bump, cv2.COLOR_RGB2GRAY)

The outputs are as follows :

Resized rgb image shape : (544, 544, 3), Mask image shape (544, 544, 1)
(544, 544, 3)
---------------------------------------------------------------------------
error                                     Traceback (most recent call last)
<ipython-input-33-07ef46f74c90> in <module>
     12     bump = tmp_mask * mask
     13     print(bump.shape)
---> 14     gray = cv2.cvtColor(bump, cv2.COLOR_RGB2GRAY)
     15 
     16     #gray_image = cv2.cvtColor(bump, cv2.COLOR_BGR2GRAY)

error: OpenCV(4.5.5) d:\a\opencv-python\opencv-python\opencv\modules\imgproc\src\color.simd_helpers.hpp:94: error: (-2:Unspecified error) in function '__cdecl cv::impl::`anonymous-namespace'::CvtHelper<struct cv::impl::`anonymous namespace'::Set<3,4,-1>,struct cv::impl::A0x7123906f::Set<1,-1,-1>,struct cv::impl::A0x7123906f::Set<0,2,5>,2>::CvtHelper(const class cv::_InputArray &,const class cv::_OutputArray &,int)'
> Unsupported depth of input image:
>     'VDepth::contains(depth)'
> where
>     'depth' is 4 (CV_32S)

How can I fix the format issue (Unsupported depth of input image) here? Is there any other simpler way to find the contours in the mask image?

CodePudding user response:

Reproduce

cv2.cvtColor(np.ones((30,30,3), dtype=np.int32), cv2.COLOR_RGB2GRAY)

Explain

depth is not the channel, it is the length of bytes for each number, int32 will use 4*8 bits to represent an integer, and uint8 just uses 1*8 bits.

cv2 needs np.float32, or np.uint8 as dtype.

We can guess tmp_mask.dtype == np.uint8

So, please check the dtype of the mask variable by print(mask.dtype)

  • Related