Skip to content Skip to sidebar Skip to footer

Can't Convert Image To Grayscale When Using Opencv

I have a transparent logo that I want to convert to grayscale using OpenCV. I am using the following code def to_grayscale(logo): gray = cv2.cvtColor(logo, cv2.COLOR_RGB2GRAY)

Solution 1:

You are mixing OpenCV and PIL/Pillow unnecessarily and will confuse yourself. If you open an image with PIL, you will get a PIL Image which is doubly no use for OpenCV because:

  • OpenCV expects Numpy arrays, not PIL Images, and
  • OpenCV uses BGR ordering, not RGB ordering like PIL uses.

The same applies when saving images.

There are three possible solutions:

  • stick to PIL
  • stick to OpenCV
  • convert every time you move between the two packages.

To convert from PIL Image to OpenCV's Numpy array:

OCVim = np.array(PILim)

To convert from OpenCV's Numpy array to PIL Image:

PILim = Image.fromarray(OCVim)

To reverse the colour ordering, not necessary with greyscale obviously, either use:

BGRim = cv2.cvtColor(RGBim, cv2.COLOR_RGB2BGR)

or use a negative Numpy stride:

BGRim = RGBim[..., ::-1]

Post a Comment for "Can't Convert Image To Grayscale When Using Opencv"