python中PIL.Image,OpenCV,Numpy图像格式相互转换

Posted 任重道远-HSY

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python中PIL.Image,OpenCV,Numpy图像格式相互转换相关的知识,希望对你有一定的参考价值。

元组和列表

a = (1, 2)      # a is a tuple 
b = list(a)     # b is a list 
c = tuple(b)  # c is a tuple

元组列表转和ndarray 数组之间转换

a = (1, 2)          # a is a tuple 
b = np.array(a)  # b is an numpy array 
c = tuple(b)       # c is a tuple 
a = [1, 2]          # a is a python array 
b = np.array(a)  # b is a numpy array 
c = list(b)          # c is a python list

Convert between OpenCV image and PIL image

 1 # color image 
 2 cimg = cv.LoadImage("ponzo.jpg", cv.CV_LOAD_IMAGE_COLOR)     # cimg is a OpenCV image
 3 pimg = Image.fromstring("RGB", cv.GetSize(cimg), cimg.tostring())    # pimg is a PIL image 
 4 cimg2 = cv.CreateImageHeader(pimg.size, cv.IPL_DEPTH_8U, 3)      # cimg2 is a OpenCV image 
 5 cv.SetData(cimg2, pimg.tostring())
 6 
 7 Note: OpenCV stores color image in BGR format. So, the converted PIL image is also in BGR-format. The standard PIL image is stored in RGB format. 
 8 
 9 # gray image 
10 cimg = cv.LoadImage("ponzo.jpg", cv.CV_LOAD_IMAGE_GRAYSCALE)   # cimg is a OpenCV image 
11 pimg = Image.fromstring("L", cv.GetSize(cimg), cimg.tostring())                 # img is a PIL image 
12 cimg2 = cv.CreateImageHeader(pimg.size, cv.IPL_DEPTH_8U, 1)              # img2 is a OpenCV image
13 cv.SetData(cimg2, pimg.tostring())

Convert between PIL image and NumPy ndarray

image = Image.open(“ponzo.jpg”)   # image is a PIL image 
array = numpy.array(image)          # array is a numpy array 
image2 = Image.fromarray(array)   # image2 is a PIL image 

Convert between PIL image and PyOpenCV matrix

image = Image.open(“ponzo.jpg”)                  # image is a PIL image
mat = pyopencv.Mat.from_pil_image(image)  # mat is a PyOpenCV matrix 
image2 = mat.to_pil_image()                        # image2 is a PIL image

Convert between OpenCV image and NumPy ndarray

cimg = cv.LoadImage("ponzo.jpg", cv.CV_LOAD_IMAGE_COLOR)   # cimg is a OpenCV image 
pimg = Image.fromstring("RGB", cv.GetSize(cimg), cimg.tostring())  # pimg is a PIL image 
array = numpy.array(pimg)     # array is a numpy array 
pimg2 = cv.fromarray(array)    # pimg2 is a OpenCV image

 

以上是关于python中PIL.Image,OpenCV,Numpy图像格式相互转换的主要内容,如果未能解决你的问题,请参考以下文章

路径名太长,尝试在 Python 中使用 OpenCV 或 PIL.Image 保存图像时出错

OpenCV转换成PIL.Image格式

基于python-opencv和PIL的截取视频区域生成 GIF 动图

torchvision中的resize对PIL.Image对象的处理速度要优于opencv近7千倍

torchvision中的resize对PIL.Image对象的处理速度要优于opencv近7千倍

Python工具类之PIL.Image库快速实现多图拼接