Chrisp
Chrisp

Reputation: 45

Convert an image between PIL to OpenCV Python 3.6.3

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

Answers (3)

Hafizur Rahman
Hafizur Rahman

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

user1767754
user1767754

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

Jason
Jason

Reputation: 11363

Use a tempfile

Untested code:

temp_file = TemporaryFile()
with open('path/to/pic.jpg', 'wb') as f:
   temp_file.write(f)
   temp_file.seek(0)

pil_img = Image.open(temp_file)
cv_img = cv2.imread(temp_file)

Upvotes: 0

Related Questions