码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2020-05-23 16:15:57      阅读:70      评论:0      收藏:0      [点我收藏+]

标签:ade   red   bsp   相互转换   tor   from   creat   enc   format   

元组和列表

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图像格式相互转换

标签:ade   red   bsp   相互转换   tor   from   creat   enc   format   

原文地址:https://www.cnblogs.com/hsy1941/p/12942897.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!