python - 使用 OpenCV/Python 读取和保存 12 位原始拜耳图像

标签 python numpy opencv

我正在尝试使用 Python 和 openCV 读取并保存 12 位原始文件。我使用的代码保存了图像,但保存的图像出现乱码/扭曲。

图像来自 FLIR Oryx 相机 23MP (5320x4600) 12 位,采用 BayerRG12P 像素格式,应为 RG GB bayer 模式。

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 位打包)

Raw files download

** 我的最终目标是使用 openCV 处理包含 RAW 图像序列的文件夹,并将它们处理/转换为另一种高分辨率格式,如 DPX 10bit 或同等格式。

我对此很陌生 - 感谢您的帮助。

编辑#1:添加屏幕截图,其中包含 FLIR 手册中有关所用 12 位格式的信息。

Link to 12 bit channel image formats (packed and regular)

最佳答案

我们可以重复使用我在以下内容中的答案 post .

OpenCV 不支持 DPX 10 位图像格式。
您可以使用 Tiff 格式或 16 位 PNG,但您可能需要将像素缩放 16(将 12 位放在 16 位的上部)。


代码示例:

import cv2
import numpy as np

width = 5320
height = 4600

with open("RG12P.Raw", "rb") as rawimg:
    # Read the packed 12bits as bytes - each 3 bytes applies 2 pixels
    data = np.fromfile(rawimg, np.uint8, width * height * 3//2)

    data = data.astype(np.uint16)  # Cast the data to uint16 type.
    result = np.zeros(data.size*2//3, np.uint16)  # Initialize matrix for storing the pixels.

    # 12 bits packing: ######## ######## ########
    #                  | 8bits| | 4 | 4  |  8   |
    #                  |  lsb | |msb|lsb |  msb |
    #                  <-----------><----------->
    #                     12 bits       12 bits
    result[0::2] = ((data[1::3] & 15) << 8) | data[0::3]
    result[1::2] = (data[1::3] >> 4) | (data[2::3] << 4)
    bayer_im = np.reshape(result, (height, width))

    # Apply Demosacing (COLOR_BAYER_BG2BGR gives the best result out of the 4 combinations).
    bgr = cv2.cvtColor(bayer_im, cv2.COLOR_BAYER_BG2BGR)  # The result is BGR format with 16 bits per pixel and 12 bits range [0, 2^12-1].

    # Show image for testing (multiply by 16 because imshow requires full uint16 range [0, 2^16-1]).
    cv2.imshow('bgr', cv2.resize(bgr*16, [width//10, height//10]))
    cv2.waitKey()
    cv2.destroyAllWindows()

    # Convert to uint8 before saving as JPEG (not part of the conversion).
    colimg = np.round(bgr.astype(float) * (255/4095))
    cv2.imwrite("test.jpeg", colimg)

结果:
enter image description here

关于python - 使用 OpenCV/Python 读取和保存 12 位原始拜耳图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70515648/

相关文章:

c++ - opencv分割返回黑色图像

python - 多个进程之间共享配置变量

带请求的 Python 网页抓取 - 登录后

python - 使用位掩码查找数据间隙

python - 根据描述,numpy.linalg.lstsq rcond 参数是否不起作用?

c++ - 使: Nothing to be done for `all' on Eclipse CDT

c++ - 每 10 帧图像平均一次

python - 无法使用 python mechanize 从网站访问表单

python - 用于近似积分的自定义函数的未知错误

numpy - 在 3D 数组的每个 2D 切片上的随机位置填充 block