【问题标题】:OpenCV merge failing to merge image channelOpenCV合并无法合并图像通道
【发布时间】:2019-09-08 04:18:05
【问题描述】:

我正在尝试将高斯噪声添加到图像的单个通道中。

import cv2 as cv
import numpy as np

img1 = cv.imread('input/foo.png')
img1_blue, img1_green, img1_red = cv.split(img1)
img1_h, img1_w, _ = img1.shape

s = 5
noise = np.random.normal(0, s, (img1_h, img1_w))
img1_gn = img1_green + noise

print(img1_green.shape) # (512, 384)
print(img1_gn.shape)    # (512, 384)
print(img1_blue.shape)  # (512, 384)

img1_g_noise = cv.merge((img1_blue, img1_gn, img1_red))

这会导致以下错误:

---------------------------------------------------------------------------
error                                     Traceback (most recent call last)
<ipython-input-34-049cf9e65133> in <module>
     13 
---> 14 img1_g_noise = cv.merge((img1_blue, img1_gn, img1_red))
     15 

error: OpenCV(3.4.5) /io/opencv/modules/core/src/merge.cpp:293: error: (-215:Assertion failed) mv[i].size == mv[0].size && mv[i].depth() == depth in function 'merge'

我不确定这是如何发生的,或者为什么会发生。生成的嘈杂绿色通道与其他两个通道具有相同的尺寸和类型。重新组合原来的绿色通道就可以了。任何转向方向表示赞赏,并提前感谢您。

【问题讨论】:

    标签: python-3.x numpy opencv


    【解决方案1】:

    这是因为噪声和通道数据类型不匹配。 numpy 矩阵的默认数据类型为 numpy.float64。并且您必须通过将.astype(img1_blue.dtype) 添加到噪声防御来定义 rach 通道类型的噪声。

    编辑代码:

    import cv2 as cv
    import numpy as np
    
    img1 = cv.imread('list.JPG')
    img1_blue, img1_green, img1_red = cv.split(img1)
    img1_h, img1_w, _ = img1.shape
    
    s = 5
    noise = np.random.normal(0, s, (img1_h, img1_w)).astype(img1_blue.dtype)
    img1_gn = img1_green + noise
    
    print(img1_green.shape) # (512, 384)
    print(img1_gn.shape)    # (512, 384)
    print(img1_blue.shape)  # (512, 384)
    
    img1_g_noise = cv.merge((img1_blue, img1_gn, img1_red))
    cv.imshow("img1_g_noise",img1_g_noise)
    cv2.waitKey()
    

    【讨论】:

      【解决方案2】:

      这是dtype 问题。

      默认情况下,image_blueimage_reduint8 类型; 但noisefloat16 类型。


      解决方案1

      您可以通过以下方式将noise 更改为 'unint8` 类型:

      noise = noise.astype('image_red.type')
      

      但这会让噪音损失很多信息。


      解决方案2

      您还可以通过添加以下两行将所有 rgb 通道更改为 float16 dtype:

      img1_blue = img1_blue.astype(img1_gn.dtype)
      img1_red = img1_red.astype(img1_gn.dtype)
      

      【讨论】:

        猜你喜欢
        • 2017-10-22
        • 2019-02-27
        • 1970-01-01
        • 2017-07-07
        • 1970-01-01
        • 1970-01-01
        • 2016-01-19
        • 2013-07-09
        • 1970-01-01
        相关资源
        最近更新 更多