Reputation: 45
How would one pass an image from PIL to OpenCV without having to save and reload it?
import cv2
import numpy as np
from PIL import Image
img = Image.open('path/to/pic.jpg')
#modify picture using PIL
img.save('path/to/pic.jpg')
img = cv2.imread("pic.jpg")
Upvotes: 1
Views: 4309
Reputation: 2370
The following worked for Python 3.7.3
:
from PIL import Image
from cv2 import cvtColor, COLOR_BGR2RGB
from numpy import array
# get the image path
img_path = 'images/test.jpg'
img_rgb = cvtColor(array(Image.open(img_path)), COLOR_BGR2RGB)
Upvotes: 2
Reputation: 25154
You can access the bytes and construct your numpy array (cv2 is internally using numpy too to store their data).
def imageToNumpy():
with Image.open('dark.jpg') as img:
nparray = np.fromstring(img.tobytes(), dtype=np.uint8)
nparray = nparray.reshape((img.size[1], img.size[0], img.layers))
return nparray
cv2.imwrite("testme.png", imageToNumpy() )
Upvotes: 1