圖像與原始字節之間的轉換
是在閱讀了《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()