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.
| # 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) |
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
If the PIL image has four bands, only reverse the first three.