将灰度图像中的像素转换为黑色(OpenCV)会导致意外结果?

时间:2018-03-02 18:59:27

标签: python opencv

我正在尝试手动遮罩图像,以便只能看到图像的圆形区域。我试图通过指定圆的中心和半径 - 图像中心到每个像素的距离来实现这一点,如果该距离大于半径,我将该像素变为黑色。

我的输入图像全白(用于测试目的),并且是6000x4000像素。 中心为(3224,2032),半径为1810像素。

处理之后,我得到了这张掩盖不好的图像

此处,蓝色圆圈是我预期不会更改的区域:预期结果

发生了什么事?

编辑:我切换了xMax和yMax的索引。这一变化产生了这一结果

import cv2
def mask (img, Xcenter, Ycenter, radius):
    radius2 = float(radius**2.00)
    Xcenter = float(Xcenter)
    Ycenter = float(Ycenter)
    img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

    imgSize = img.shape
    xMax = imgSize[0]
    yMax = imgSize[1]

    print("Drawing mask...")

    for y in range(1,yMax):
        for x in range(1,xMax):
            dist2 = int(((x - Xcenter)**2 + (y - Ycenter)**2))
            try:
                if dist2 >= radius2:
                    img[x, y] = 0
            except IndexError:
                pass
                #print ("Index error: X = ", x, " Y = ", y)
                #char = input("Press enter to continue")
    cv2.imwrite("maskedImg.tif", img)
    print("Completed mask.")
    return img

2 个答案:

答案 0 :(得分:0)

.shape返回图像的行数/列数/通道数。

.size返回像素数。

这些很可能会有所不同,因此当您使用圆圈功能引用像素时,它们不会按照您的预期排列。

答案 1 :(得分:0)

看起来你混淆了x和y。 “行”的数量为Y,所以

yMax = imgSize[0]
xMax = imgSize[1]

请记住,点(0,0)位于左上角。 另外,为了进行测试,我建议先将你的圈子放在中心位置。它并不重要,但有时你可以在图片中更容易地调试这些东西。