1. opencv 和 bytes
def mat2bytes(image: np.ndarray) -> bytes:
return np.array(cv2.imencode('.jpg', image)[1]).tobytes()
def bytes2mat(image: bytes) -> np.ndarray:
return cv2.imdecode(np.array(bytearray(image), dtype='uint8'), cv2.IMREAD_UNCHANGED)
2. opencv 和 base64
def mat2base64(image: np.ndarry) -> str:
return str(base64.b64encode(cv2.imencode('.jpg',image)[1]))[2:-1]
def base642mat(image: str) -> np.ndarry:
return cv2.imdecode(np.fromstring(base64.b64decode(image), np.uint8), cv2.IMREAD_COLOR)
3. opencv 和 PIL
def mat2image(image: np.ndarry) -> Image:
return Image.fromarray(cv2.cvtColor(image,cv2.COLOR_BGR2RGB))
def image2mat(image: Image) -> np.ndarry:
return cv2.cvtColor(np.asarray(image),cv2.COLOR_RGB2BGR)
4. bytes 和 base64
def bytes2base64(image: bytes) -> str:
return base64.b64encode(image).decode()
def base642bytes(image: str) -> bytes:
return base64.b64decode(image)
5. opencv 和 QImage
def mat2qimage(image: np.ndarry) -> QImage:
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
y, x = image.shape[:2]
return QImage(image.data, x, y, x * 3, QImage.Format_RGB888)
def qimage2mat(image: QImage) -> np.ndarry:
image = image.convertToFormat(4)
width = image.width()
height = image.height()
ptr = image.bits()
ptr.setsize(image.byteCount())
return np.array(ptr).reshape(height, width, 4)
6. opencv 和 matplotlib
import matplotlib.pyplot as plt
import cv2
image = cv2.imread("./")
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
plt.imshow(image)
plt.savefig('./')
plt.show()