Python 将图像从 PIL 转换为 openCV 格式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14134892/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert image from PIL to openCV format
提问by md1hunox
I'm trying to convert image from PILto OpenCVformat. I'm using OpenCV 2.4.3.
here is what I've attempted till now.
我正在尝试将图像转换PIL为OpenCV格式。我正在使用OpenCV 2.4.3. 这是我迄今为止所尝试的。
>>> 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()
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 PILto CVformat?
但我认为图像没有转换为 CV 格式。窗口向我展示了一个大的棕色图像。将图像从格式转换PIL为CV格式时我哪里出错了?
Also , why do i need to type cv.cvto access functions?
另外,为什么我需要输入cv.cv才能访问功能?
采纳答案by Abhishek Thakur
use this:
用这个:
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()
回答by Berthier Lemieux
This is the shortest version I could find,saving/hiding an extra conversion:
这是我能找到的最短版本,保存/隐藏额外的转换:
pil_image = PIL.Image.open('image.jpg')
opencvImage = cv2.cvtColor(numpy.array(pil_image), cv2.COLOR_RGB2BGR)
If reading a file from a URL:
如果从 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)

