The story that it turns blue when the data read by Pillow is converted so that it can be handled by OpenCV

I want to do detailed processing with OpenCV, but I want to do file input / output with Pillow! Or rather, if you save it with OpenCV, it will be a file ... There are times.

That's why I wrote a sample Pillow-> OpenCV and OpenCV-> Pillow.

from PIL import Image
import cv2
import numpy as np

#Load images with PIL data
im = Image.open('t.jpg')

#Convert to OpenCV data
ocv_im = np.asarray(im)

#Save with OpenCV
cv2.imwrite("t_ocv.jpg ",ocv_im)

#Convert to PIL data
pil_im = Image.fromarray(ocv_im)
#Save as PIL
pil_im.save("t_pil.jpg ")

The file that came out in.

t_ocv.jpg t_ocv.jpg

t_pil.jpg t_pil.jpg

For some reason t_ocv.jpg is blue as close to blue as possible.

When I looked it up, OpenCV said that the color was BGR instead of RGB.

So if you convert ocv_im to RGB, there is no problem.

cv2.imwrite("t_ocv.jpg ",ocv_im)

cv2.imwrite("t_ocv.jpg ",ocv_im[:, :, ::-1].copy())

Solution. that's all.

Recommended Posts

The story that it turns blue when the data read by Pillow is converted so that it can be handled by OpenCV
Read the image posted by flask so that it can be handled by opencv
Deep Learning! The story of the data itself that is read when it does not follow after handwritten number recognition
Since python is read as "Pichon", it can be executed with "Pichon" (it is a story)
I tried to make OneHotEncoder, which is often used for data analysis, so that it can reach the itch.
It is a piggybacking story about the service that returns "Nyan" when you ping
List the classes that can be referenced by ObjCClass
I tried to expand the database so that it can be used with PES analysis software
Normalize the file that converted Excel to csv as it is.
The story that the guard was confined when the laboratory was converted to IoT
[Python] When the priority is the same in Priority Queue, it can be acquired in the order in which it was added to the queue.