Bands need to be reversed for CV2. PIL is RGB. CV2 is BGR.
Also, if you are getting errors with CV2, it may be because it doesn’t like transformed ‘views’ of arrays. Use the copy method.
Cv2 Rgb To Gray Paint
Filenames = gl.glob('flowerimages.png') count = 1 for file in filenames: img = cv2.imread(file, 0) img = cv2.resize(img, (128, 128)) cv2.imwrite('actualgraytest/gray' +str(count) +'.jpg', img) count += 1 We import all the training and testing datasets which will be used by the autoencoder. It also does this when using cv2.cvtColor(img, cv2.COLORBGR2RGB). In my case, I'm debayering a greyscale image and then saving as a 3 channel colour image. When saving both the 'rgb' and 'bgr' images, they turn out identical, and clearly are saving an rgb image as though it's bgr with red things appearing blue and vice versa. Steps to reproduce. And as you see, the conversion back to color is only adding the gray scale value to the 3 channels of colors RGB. Why do we lose information? The key to understand is that a color image has three channels for each pixel, while a gray scale image only has one channel.
# PIL RGB 'im' to CV2 BGR 'imcv' |
imcv=np.asarray(im)[:,:,::-1].copy() |
# Or |
imcv=cv2.cvtColor(np.asarray(im), cv2.COLOR_RGB2BGR) |
# To gray image |
imcv=np.asarray(im.convert('L')) |
# Or |
imcv=cv2.cvtColor(np.asarray(im), cv2.COLOR_RGB2GRAY) |
Consider a color image, given by its red, green, blue components R, G, B. The range of pixel values is often 0 to 255. Color images are represented as multi-dimensional arrays - a collection of three two-dimensional arrays, one each for red, green, and blue channels. Each one has one value per pixel and their ranges are identical. For grayscale images, the result is a two-dimensional array.
PIL and CV2 use the same percentages of R,G, and B to make a greyscale image but the results may have a difference of 1 in many places due to rounding off. PIL uses integer division and CV2 uses floating point percentages.
PIL: GRAY = R * 299/1000 + G * 587/1000 + B * 114/1000
CV2: GRAY = R * 0.299 + G * 0.587 + B * 0.114
Cv2 Convert Gray To Rgb
If the PIL image has four bands, only reverse the first three.