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

2021-01-14 09:11

阅读:439

标签: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


评论


亲,登录后才可以留言!