Convert image from PIL to openCV format

Each Answer to this Q is separated by one/two green lines.

I’m trying to convert image from PIL to OpenCV format. I’m using OpenCV 2.4.3.
here is what I’ve attempted till now.

>>> from PIL import Image
>>> import cv2 as cv
>>> pimg ='D:\\traffic.jpg')                           #PIL Image
>>> cimg =,cv.IPL_DEPTH_8U,3)    #CV Image

But I think the image is not getting converted to CV format. The Window shows me a large brown image.
Where am I going wrong in Converting image from PIL to CV format?

Also , why do i need to type to access functions?

use this:

pil_image ='Image.jpg').convert('RGB') 
open_cv_image = numpy.array(pil_image) 
# Convert RGB to BGR 
open_cv_image = open_cv_image[:, :, ::-1].copy() 

This is the shortest version I could find,saving/hiding an extra conversion:

pil_image ='image.jpg')
opencvImage = cv2.cvtColor(numpy.array(pil_image), cv2.COLOR_RGB2BGR)

If reading a file from a URL:

import cStringIO
import urllib
file = cStringIO.StringIO(urllib.urlopen(r'').read())
pil_image =
opencvImage = cv2.cvtColor(numpy.array(pil_image), cv2.COLOR_RGB2BGR)

The code commented works as well, just choose which do you prefer

import numpy as np
from PIL import Image

def convert_from_cv2_to_image(img: np.ndarray) -> Image:
    # return Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
    return Image.fromarray(img)

def convert_from_image_to_cv2(img: Image) -> np.ndarray:
    # return cv2.cvtColor(numpy.array(img), cv2.COLOR_RGB2BGR)
    return np.asarray(img)

Here are two functions to convert image between PIL and OpenCV:

def toImgOpenCV(imgPIL): # Conver imgPIL to imgOpenCV
    i = np.array(imgPIL) # After mapping from PIL to numpy : [R,G,B,A]
                         # numpy Image Channel system: [B,G,R,A]
    red = i[:,:,0].copy(); i[:,:,0] = i[:,:,2].copy(); i[:,:,2] = red;
    return i; 

def toImgPIL(imgOpenCV): return Image.fromarray(cv2.cvtColor(imgOpenCV, cv2.COLOR_BGR2RGB));

Convert from OpenCV img to PIL img will lost transparent channel. While convert PIL img to OpenCV img will able to keep transparent channel, although cv2.imshow not display it but save as png will gave result normally.

  • You can call cv2.imwrite(“./”+”fileName.png”, img); to export and check the transparent result of OpenCV img.
  • Or toImgPIL(img).save(‘test.png’, ‘PNG’) to check PIL img.

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Leave a Reply

Your email address will not be published.