Convert opencv image format to PIL image format?

I want to convert the downloaded image

TestPicture = cv2.imread("flowers.jpg")

I would like to run the PIL filter ( http://pillow.readthedocs.io/en/4.0.x/reference/ImageFilter.html ), as in the example https://wellfire.co/learn/python-image-enhancements/ with variable

TestPicture

but I can’t convert it back and fourth between these types.

Is there any way to do this conversion?

Can opencv do all the image filters that are in the PIL package?

+4
source share
2 answers

OpenCV . , OpenCV > API.

, OpenCV PIL, Image.fromarray :

import cv2
import numpy as np
from PIL import Image

img = cv2.imread("path/to/img.png")

# You may need to convert the color.
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
im_pil = Image.fromarray(img)

# For reversing the operation:
im_np = np.asarray(im_pil)

, OpenCV BGR , PIL RGB, cv2.cvtColor() .

+8

Pillow OpenCV . , Pillow OpenCV. RGB, @ZdaR, OpenCV BGR. , .

PIL OpenCV :

import cv2
import numpy as np
from PIL import Image

pil_image=Image.open("demo2.jpg") # open image using PIL

# use numpy to convert the pil_image into a numpy array
numpy_image=numpy.array(pil_img)  

# convert to a openCV2 image, notice the COLOR_RGB2BGR which means that 
# the color is converted from RGB to BGR format
opencv_image=cv2.cvtColor(numpy_image, cv2.COLOR_RGB2BGR) 

OpenCV PIL :

import cv2
import numpy as np
from PIL import Image

opencv_image=cv2.imread("demo2.jpg") # open image using openCV2

# convert from openCV2 to PIL. Notice the COLOR_BGR2RGB which means that 
# the color is converted from BGR to RGB
pil_image=cv2.cvtColor(opencv_image, cv2.COLOR_BGR2RGB) 
+1

Source: https://habr.com/ru/post/1674099/


All Articles