-1

Seems like cv2.imread() or Image.fromarray() is changing original image color to a bluish color. What i am trying to accomplish is to crop the original png image and keep the same colors but the color changes. Not sure how to revert to original color. Please help! ty `

                    # start cropping logic
                    img = cv2.imread("image.png") # import cv2
                    crop = img[1280:, 2250:2730]
                    cropped_rendered_image = Image.fromarray(crop) #from PIL import Image
                    cropped_rendered_image.save("newImageName.png") 
          

`

tried this and other fixes but no luck yet https://stackoverflow.com/a/50720612/13206968

Christoph Rackwitz
  • 11,317
  • 4
  • 27
  • 36
  • Does this answer your question? [why cv2.imwrite() changes the color of pics?](https://stackoverflow.com/questions/42406338/why-cv2-imwrite-changes-the-color-of-pics) – Dan Mašek Nov 24 '22 at 23:33

1 Answers1

2

There is no "changing" going on. It's simply a matter of channel order.

  • OpenCV natively uses BGR order (in numpy arrays)
  • PIL natively uses RGB order
  • Numpy doesn't care

When you call cv.imread(), you're getting BGR data in a numpy array.

When you repackage that into a PIL Image, you are giving it BGR order data, but you're telling it that it's RGB, so PIL takes your word for it... and misinterprets the data.

You can try telling PIL that it's BGR;24 data. See https://pillow.readthedocs.io/en/stable/handbook/concepts.html

Or you can use cv.cvtColor() with the cv.COLOR_BGR2RGB flag (because you have BGR and you want RGB). For the opposite direction, there is the cv.COLOR_RGB2BGR flag.

Christoph Rackwitz
  • 11,317
  • 4
  • 27
  • 36