圖像與原始字節之間的轉換

圖像與原始字節之間的轉換

是在閱讀了《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()
發佈了27 篇原創文章 · 獲贊 12 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章