Image格式转换

吴驰
2023-12-01

PIL.Image转换成OpenCV格式:

import cv2
from PIL import Image
import numpy
path = '1.jpg'
img = Image.open(path).convert("RGB")#.convert("RGB")可不要,默认打开就是RGB
img.show()
"""key line PIL-->CV"""
#img = cv2.cvtColor(numpy.asarray(image),cv2.COLOR_RGB2BGR)
img = cv2.cvtColor(np.array(img),cv2.COLOR_RGB2BGR)
cv2.imshow("OpenCV",img)
cv2.waitKey()

OpenCV转换成PIL.Image格式:

import cv2
from PIL import Image
import numpy
img = cv2.imread("1.jpg") # opencv打开的是BRG
cv2.imshow("OpenCV",img)
"""key line CV-->PIL"""
image = Image.fromarray(cv2.cvtColor(img,cv2.COLOR_BGR2RGB))
image.show()
cv2.waitKey()

判断图像数据是否是OpenCV格式:

isinstance(img, np.ndarray)

OpenCV转换成二进制:

import cv2
from PIL import Image
import numpy as np
import io
from baidu.person_detect import person_detect_byte

#读取网络摄像头
#camera = cv2.VideoCapture('rtsp://admin:password@10.0.10.1:554/h264/ch1/main/av_stream')

#读取本地摄像头
camera = cv2.VideoCapture (0)

success, image = camera.read ()
cv2.imshow("xxxx",image)
cv2.waitKey (5000)
imgRGB = cv2.cvtColor (image, cv2.IMREAD_COLOR)
# 将图片格式转换(编码)成流数据,赋值到内存缓存中;主要用于图像数据格式的压缩,方便网络传输。
r, buf = cv2.imencode (".jpg", imgRGB)

#array转换成image
bytes_image = Image.fromarray (np.uint8 (buf)).tobytes ()
#array转换成二进制
# image = io.BytesIO (bytes_image)

JpegImageFile转换成二进制:


from io import BytesIO
img = Image.open('/home/hensel/Desktop/1.jpg')

# Create a buffer to hold the bytes
buf = BytesIO()

# Save the image as jpeg to the buffer
img.save(buf, 'jpeg')

# Rewind the buffer's file pointer
buf.seek(0)

# Read the bytes from the buffer
image_bytes = buf.read()
# res=person_detect_byte(image_bytes)
# print(res)

# Close the buffer
buf.close()

参考:
https://blog.csdn.net/Gavinmiaoc/article/details/83614833

 类似资料: