Skip to content

Instantly share code, notes, and snippets.

@Roger8
Last active September 8, 2022 09:42
Show Gist options
  • Save Roger8/908307beae3eb6e611bf266dd85007f1 to your computer and use it in GitHub Desktop.
Save Roger8/908307beae3eb6e611bf266dd85007f1 to your computer and use it in GitHub Desktop.
python中 【PIL.Image,OpenCV,Numpy, 二进制流, base64编码 】之间图像格式相互转换

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

numpy array
opencv 
PIL Image
base64.b64encode
str

# 获取图片的二进制数据
open('x.jpg', 'rb') as gbindata = g.read()
binbytes = urllib2.urlopen('http://www.test.com/x.jpg').read()
# binbytes与直接以rb二进制读图片文件获取的数据bindata完全一样,同为字节流,数据类型为str

#io.BytesIO():#Create a buffered I/O implementation using an in-memory bytes
# |  buffer, ready for reading and writing.
iobuf = io.BytesIO(bindata) # 二进制字节转换为iobuffer
# iobuffer 对象通过PIL的open函数打开获得PIL图像实例
im = Image.open(iobuf)
#In [300]: im.size
#Out[300]: (480, 640)
mat =  np.asarray(im) # 转换PIL的img对象为numpy的array
#In [314]: mat.shape
#Out[314]: (640L, 480L, 3L)

b64bytes = base64.encode(binbytes) # 2进制字节流str经base64编码后str
#In [274]: len(binbytes)
#Out[274]: 95464
#In [279]: len(b64bytes)*3/4 -bda64.count('=',-2) # 
#Out[279]: 95464

npa = np.frombuffer(binbytes, np.uint8) # or np.fromstring(bytestr,np.uint8)
#In [295]: npa.shape
#Out[295]: (95464L,)
img = cv2.imdecode(npa, cv2.IMREAD_COLOR)
#In [299]: img.shape
#Out[299]: (640L, 480L, 3L)

imec = cv2.imencode('.jpg', mat)
#In [320]: imec
#Out[320]:
#(True, array([[255],
#        [216],
#        [255],
#        ...,
#        [153],
#        [255],
#        [217]], dtype=uint8))
#In [321]: imec[1].shape
#Out[321]: (63495L, 1L)  # imagemat(640L, 480L, 3L)经imencode编码后大小
imec[1].tobytes() # 或imec[1].tostring() 转换mat为字节流
#Convert between NumPy 2D array and NumPy matrix

a = numpy.ndarray([2,3])# create 2x3 array
m1 = numpy.asmatrix(a)# does not create new matrix, m1 refers to the same memory as a 
m2 = numpy.matrix(a)# creates new matrix and copies content 
 
b1 = numpy.asarray(m2)# does not create array, b1 refers to the same emory as m2
b2 = numpy.array(m2)# creates new array and copies content
Read/Write Images with OpenCV

image = cv.LoadImage(“ponzo.jpg”)
cv.SaveImage(“out.png”, image)
Read/Write Images with PIL

image = Image.open(“ponzo.jpg”)
image.save(“out.jpg”)
Read/Write Images with PyOpenCV

mat = cv2.imread(“ponzo.jpg”)
cv2.imwrite(“out.png”, mat)
#Convert between OpenCV image and PIL image

# color image 
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 
cimg2 = cv.CreateImageHeader(pimg.size, cv.IPL_DEPTH_8U, 3)# cimg2 is a OpenCV image 
cv.SetData(cimg2, pimg.tostring())
 
#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. 
 
# gray image 
cimg = cv.LoadImage("ponzo.jpg", cv.CV_LOAD_IMAGE_GRAYSCALE)# cimg is a OpenCV image 
pimg = Image.fromstring("L", cv.GetSize(cimg), cimg.tostring())  # img is a PIL image 
cimg2 = cv.CreateImageHeader(pimg.size, cv.IPL_DEPTH_8U, 1)  # img2 is a OpenCV image
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 = cv2.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
还可以参考这样形式的代码PIL.Image转换成OpenCV格式import cv2  
from PIL import Image  
import numpy  
 
image = Image.open("plane.jpg")  
image.show()  
img = cv2.cvtColor(numpy.asarray(image),cv2.COLOR_RGB2BGR)  
cv2.imshow("OpenCV",img)  
cv2.waitKey()

OpenCV转换成PIL.Image格式import cv2  
from PIL import Image  
import numpy  
 
img = cv2.imread("plane.jpg")  
cv2.imshow("OpenCV",img)  
image = Image.fromarray(cv2.cvtColor(img,cv2.COLOR_BGR2RGB))  
image.show()  
cv2.waitKey()

#numpy array 转 PIL Image 
img = Image.fromarray(img.astype('uint8')).convert('RGB')
# save img
img.save("t.jpg")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment