我正在嘗試使用 Python 和 openCV 讀取和保存 12 位原始檔案。我使用的代碼保存了一個影像,但保存的影像是亂碼/扭曲的。
影像來自 FLIR Oryx 相機 23MP (5320x4600) 12Bit,采用 BayerRG12P 像素格式,應該是 RG GB 拜耳圖案。
import cv2
import numpy as np
width = 5320
height = 4600
with open("aaa12packed.Raw", "rb") as rawimg:
img = np.fromfile(rawimg, np.dtype('u1'), width * height).reshape(height, width)
colimg = cv2.cvtColor(img, cv2.COLOR_BAYER_GR2RGB)
cv2.imwrite("test.jpeg", colimg)
我上傳了兩個用于測驗 debayer/demoisaic 的原始檔案。您可以使用以下鏈接下載它們:
“RG12P.Raw”(這是 12 位正則)和“RG12packed.Raw”(這是 12 位打包)

uj5u.com熱心網友回復:
我不確定您共享的兩個檔案之間的區別,但這里有一種相當快速的技術來讀取和解壓 12 位樣本。我不太確定你真正想要什么,所以我已經放了很多除錯代碼和注釋,所以你可以看到我在做什么,然后你可以微調。
不要被代碼的長度所拖延,我在評論中只對 4 行進行了編號:
#!/usr/bin/env python3
# Demosaicing Bayer Raw image
import cv2
import numpy as np
filename = 'RG12P.Raw'
# Set width and height
w, h = 5320, 4600
# Read entire file and reshape as rows of 3 bytes
bayer = np.fromfile(filename, dtype=np.uint8).reshape((-1,3)) # LINE 1
print(f'DEBUG: bayer.shape={bayer.shape}')
for i in 0,1,2:
print(f'DEBUG: bayer[{i}]={bayer[i]}')
# Make each 3-byte row into a single np.uint32 containing 2 samples of 12-bits each
bayer32 = np.dot(bayer.astype(np.uint32), [1,256,65536]) # LINE 2
print(f'DEBUG: bayer32.shape={bayer32.shape}')
for i in 0,1,2:
print(f'DEBUG: bayer32[{i}]={bayer32[i]}')
# Extract high and low samples from pairs
his = bayer32 >> 12 # LINE 3
los = bayer32 & 0xfff # LINE 4
print(f'DEBUG: his.shape={his.shape}')
for i in 0,1,2:
print(f'DEBUG: his[{i}]={his[i]}')
print(f'DEBUG: los.shape={los.shape}')
for i in 0,1,2:
print(f'DEBUG: los[{i}]={los[i]}')
# Stack into 3 channel
#BGR16 = np.dstack((B,G,R)).astype(np.uint16)
# Save result as 16-bit PNG
#cv2.imwrite('result.png', BGR16)
樣本輸出
DEBUG: bayer.shape=(12236000, 3)
DEBUG: bayer[0]=[119 209 36]
DEBUG: bayer[1]=[249 17 29]
DEBUG: bayer[2]=[ 49 114 35]
DEBUG: bayer32.shape=(12236000,)
DEBUG: bayer32[0]=2412919
DEBUG: bayer32[1]=1905145
DEBUG: bayer32[2]=2322993
DEBUG: his.shape=(12236000,)
DEBUG: his[0]=589
DEBUG: his[1]=465
DEBUG: his[2]=567
DEBUG: los.shape=(12236000,)
DEBUG: los[0]=375
DEBUG: los[1]=505
DEBUG: los[2]=561
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/397446.html
