代码之家  ›  专栏  ›  技术社区  ›  ProfK

为什么这个OpenCV阈值调用返回空白图像?

  •  0
  • ProfK  · 技术社区  · 5 年前

    我正在学习OpenCV的教程,其中使用了以下代码:

    import argparse
    import imutils
    import cv2
    
    ap = argparse.ArgumentParser()
    ap.add_argument("-i", "--image", required=True, help="path to input image")
    args = vars(ap.parse_args())
    
    image = cv2.imread(args["image"])
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    
    thresh = cv2.threshold(gray, 255, 255, cv2.THRESH_BINARY_INV)[1]
    cv2.imshow("Thresh", thresh)
    cv2.waitKey()
    

    然而,图像 thresh 显示为浅灰色背景的空白窗口,教程应该在其中展示教程源代码附带的图像的单色配置文件。

    我使用的是相同的代码和相同的输入图像,但教程告诉我需要一个显示对象轮廓的单色图像,而我只得到一个空白的灰色图像。这里可能出了什么问题?

    0 回复  |  直到 5 年前
        1
  •  0
  •   Ahmet    5 年前

    你的 thresh 参数值应不同于 maxval 价值。

    thresh = cv2.threshold(src=gray,
                           thresh=127,
                           maxval=255,
                           type=cv2.THRESH_BINARY_INV)[1]
    

    documentation

    • gray 是您的源图像。
    • 脱粒 是阈值
    • 麦克斯韦 为最大值
    • type 是阈值类型

    当你同时设置两者时 脱粒 麦克斯韦 相同的值,你说:

    我想显示255以上的像素值,但任何像素都不应超过255。

    因此,结果是一个空白图像。

    一种可能的方法是将阈值设置为127。

    例如:

    原始图像阈值图像

    enter image description here enter image description here

    import cv2
    
    image = cv2.imread("fgtc7_256_256.jpg")
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    thresh = cv2.threshold(src=gray,
                           thresh=127,
                           maxval=255,
                           type=cv2.THRESH_BINARY_INV)[1]
    cv2.imshow("Thresh", thresh)
    cv2.waitKey(0)