I have searched for similar questions, but haven't found anything helpful as most solutions use older versions of OpenCV.
I have a 3D numpy array, and I would like to display and/or save it as a BGR image using OpenCV (cv2).
As a short example, suppose I had:
import numpy, cv2 b = numpy.zeros([5,5,3]) b[:,:,0] = numpy.ones([5,5])*64 b[:,:,1] = numpy.ones([5,5])*128 b[:,:,2] = numpy.ones([5,5])*192
What I would like to do is save and display b as a color image similar to:
cv2.imwrite('color_img.jpg', b) cv2.imshow('Color image', b) cv2.waitKey(0) cv2.destroyAllWindows()
This doesn't work, presumably because the data type of b isn't correct, but after substantial searching, I can't figure out how to change it to the correct one. If you can offer any pointers, it would be greatly appreciated!
OpenCV uses BGR image format. So, when we read an image using cv2. imread() it interprets in BGR format by default. We can use cvtColor() method to convert a BGR image to RGB and vice-versa.
You don't need to convert NumPy
array to Mat
because OpenCV cv2
module can accept NumPy
array. The only thing you need to care for is that {0,1} is mapped to {0,255} and any value bigger than 1 in NumPy
array is equal to 255. So you should divide by 255 in your code, as shown below.
img = numpy.zeros([5,5,3]) img[:,:,0] = numpy.ones([5,5])*64/255.0 img[:,:,1] = numpy.ones([5,5])*128/255.0 img[:,:,2] = numpy.ones([5,5])*192/255.0 cv2.imwrite('color_img.jpg', img) cv2.imshow("image", img) cv2.waitKey()
You are looking for scipy.misc.toimage
:
import scipy.misc rgb = scipy.misc.toimage(np_array)
It seems to be also in scipy 1.0, but has a deprecation warning. Instead, you can use pillow
and PIL.Image.fromarray
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With