图像与原始字节之间的转换

图像与原始字节之间的转换

是在阅读了《opencv 3 计算机视觉 python语言实现》之后的一个代码,推荐大家去看看

图像转换成原始字节

bytearray1 = bytearray(img)

原始字节转换成图像

grayImage = np.array(bytearray1).reshape(768,1366)

完整代码

import cv2
import numpy as np
from matplotlib import pyplot as plt
import os

img = cv2.imread("test.jpg",cv2.IMREAD_GRAYSCALE)
#等效于 img = cv2.imread("test.jpg",0)
print(img.shape)
#显示转换为标准一维python bytearray
bytearray1 = bytearray(img)
# cv2.imshow("1",img)
# cv2.waitKey(0)
# cv2.destroyAllWindows()

img2 = cv2.imread("test.jpg")
bytearray2 = bytearray(img2)

#将字节转换为图像
grayImage = np.array(bytearray1).reshape(768,1366)
bgrImage = np.array(bytearray2).reshape(768,1366,3)

cv2.imshow("gray",grayImage)
cv2.imshow("bgr",bgrImage)

#将随机字节转换为灰度图像和BGR图像
random_bytearray = bytearray(os.urandom(300000))

gray_random = np.array(random_bytearray).reshape(500,600)
bgr_random = np.array(random_bytearray).reshape(500,200,3)

cv2.imshow("gray_random",gray_random)
cv2.imshow("bgr_random",bgr_random)


cv2.waitKey(0)
cv2.destroyAllWindows()

猜你喜欢

转载自blog.csdn.net/hehangjiang/article/details/75949030