0

I have a code in which the matrix hip_dir represents a RGB image. If I check its shape, python returns (1080, 1920, 3). If I write

cv2.imwrite('hip_dir.jpg',hip_dir)

I get the correct image saved in the folder. However, when I do

cv2.imshow('img0',hip_dir)
cv2.waitKey(0)
cv2.destroyAllWindows()

I get the same image, in black and white (there are some blue pixels, however, making this even stranger).

How can I use imshow correctly?

Edit:

Using the command cv2.cvtColor results in the following error:

error: OpenCV(4.1.0) c:\projects\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::A0xe227985e::Set<3,4,-1>,struct cv::impl::A0xe227985e::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 6 (CV_64F)

Edit2: I discovered that the reason for this error to occur is simple because the matrix is in np.float64. Having it converted to np.float32, however, does not change the imshow result.

Jamiu S.
  • 5,257
  • 5
  • 12
  • 34
donut
  • 628
  • 2
  • 9
  • 23
  • 2
    Adding your images (both correct and *"unhappy"* versions) to your question is always appreciated and considerably more likely to result in a useful answer when asking image processing questions... – Mark Setchell Jul 19 '19 at 09:41

2 Answers2

1

OpenCV expects the image to be in BGR format, try applying

converted = cv2.cvtColor(hip_dir,cv2.COLOR_BGR2RGB)
mark
  • 91
  • 4
1

So guys, I discovered what was wrong: the correct way to disply the RGB colors in the imshow command is forcing the correspondent matrix of the image to be in np.uint8 format. I tested the other formats, and none of them worked properly. I don't know why, though.

donut
  • 628
  • 2
  • 9
  • 23
  • 3
    The reason is that uint8 images expect values from 0..255. Images with a floating-point type expect values between 0 and 1. If you have a floating-point image with values above 1, they're all assumed to be 1. The result is a binary image with 0 = black, and 1-255 = white. – beaker Jul 19 '19 at 21:09