136 votes

Convertir l'image de PIL au format openCV

J'essaie de convertir une image de PIL a OpenCV format. J'utilise OpenCV 2.4.3 . voici ce que j'ai tenté jusqu'à présent.

>>> from PIL import Image
>>> import cv2 as cv
>>> pimg = Image.open('D:\\traffic.jpg')                           #PIL Image
>>> cimg = cv.cv.CreateImageHeader(pimg.size,cv.IPL_DEPTH_8U,3)    #CV Image
>>> cv.cv.SetData(cimg,pimg.tostring())
>>> cv.cv.NamedWindow('cimg')
>>> cv.cv.ShowImage('cimg',cimg)
>>> cv.cv.WaitKey()

Mais je pense que l'image n'est pas convertie au format CV. La fenêtre me montre une grande image brune. Où est-ce que je me trompe dans la conversion de l'image de PIL a CV format ?

Aussi, pourquoi dois-je taper cv.cv pour accéder aux fonctions ?

231voto

Abhishek Thakur Points 5868

Utilisez ça :

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

134voto

Berthier Lemieux Points 1093

C'est la version la plus courte que j'ai pu trouver, en économisant/cachant une conversion supplémentaire :

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

Si vous lisez un fichier à partir d'une URL :

import cStringIO
import urllib
file = cStringIO.StringIO(urllib.urlopen(r'http://stackoverflow.com/a_nice_image.jpg').read())
pil_image = PIL.Image.open(file)
opencvImage = cv2.cvtColor(numpy.array(pil_image), cv2.COLOR_RGB2BGR)

11voto

Pedro Nunes Points 59

Le code commenté fonctionne aussi bien, il suffit de choisir celui que vous préférez

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)

0voto

phnghue Points 1047

Voici deux fonctions pour convertir une image entre PIL et 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));

La conversion d'une image OpenCV en image PIL perd le canal transparent. Alors que la conversion de PIL img en OpenCV img sera capable de garder le canal transparent, bien que cv2.imshow ne l'affiche pas mais l'enregistrement en png donnera un résultat normal.

  • Vous pouvez appeler cv2.imwrite("./"+"nomfichier.png", img) ; pour exporter et vérifier le résultat transparent de l'img OpenCV.
  • Ou toImgPIL(img).save('test.png', 'PNG') pour vérifier l'image du LIP.

Prograide.com

Prograide est une communauté de développeurs qui cherche à élargir la connaissance de la programmation au-delà de l'anglais.
Pour cela nous avons les plus grands doutes résolus en français et vous pouvez aussi poser vos propres questions ou résoudre celles des autres.

Powered by:

X