【问题标题】:Python's cv2 gives the message "returned NULL without setting an error"Python 的 cv2 给出消息“返回 NULL 而没有设置错误”
【发布时间】:2021-04-08 06:31:51
【问题描述】:
  • 我正在尝试编写一个程序来计算图像中的 blob 数量。
  • 我已从文件中读取图像并使用PIL 将其转换为灰度。
  • 然后我将其转换为 numpy 数组,并通过一个 for 循环传递该数组,该循环将高于特定光强度的所有像素转换为白色,将所有其他像素转换为黑色。
  • 然后我使用 PIL 从该数组创建了一个新图像,一切似乎都运行良好:

  • 然后我应用了 cv2 中包含的 SimpleBlobDetector,但它给了我这个非常不具体的错误消息:

返回 NULL 且未设置错误

有谁知道这意味着什么,或者我能做些什么?到目前为止,我将包含我的代码,如果这能让事情更清楚的话。

    #Reading image from file and converting to grayscale
    filename = 'C:/Users/Windows/Desktop/Jobb/Np concentration/Microscopy images/EJ01057wellA10x.tif'
    myimg = Image.open(filename).convert('L')
    
    
    #Turning the pixels of the image into an array, and making that array editable
    imgdata = asarray(myimg)
    #print(imgdata)
    imgdata = imgdata.astype(np.float64)
    
    
    #Changing all pixels below the light intensity of 200 to black pixels, and all 
    #above to white
    for x in imgdata:
        x[x < 200] = 0 
        x[x >= 200] = 255
    
    
    #print(imgdata.shape)
    #Creating a new image from the edited array, and displaying it
    newImg = Image.fromarray(imgdata)
    newImg.show()
    
    
    #TODO: Count white blobs in newImg using a simple blob detector
    detector = cv.SimpleBlobDetector()
    keypoints = detector.detect(newImg)
    print(keypoints)

【问题讨论】:

  • 这是一个 cv2 错误。检查他们的错误跟踪器以获取现有报告,如果没有,请报告。 (确保包含足够的细节来重现错误。)
  • (您的代码也可能有误 - 我没有仔细检查过 - 但您收到的错误消息来自 cv2 错误。)
  • @EmmaJo 而不是for-loop,最好使用矢量化imgdata[imgdata&lt; 200] = 0, imgdata[imgdata&gt;200]=255

标签: python arrays opencv image-processing cv2


【解决方案1】:

您正在将 PIL Image 对象传递给 OpenCV 函数。这是不正确的用法,不是 OpenCV 中的错误。 OpenCV(在 python 中)期望图像是 numpy 数组。 edit: OpenCV 处理这种情况很糟糕,应该引发一个适当的 python 异常 (TypeError)。这是一个错误,您应该在 OpenCV 的 github 上打开一个关于此问题的问题。

其次,使用the SimpleBlobDetector_create method 创建一个实例 SimpleBlobDetector。它会按照你的方式失败。

您还应该像这样创建参数:

params = cv.SimpleBlobDetector_Params()
params.filterByArea = ... # True/False, if you need it
params.maxArea = ...
# and other attributes. see docs.
detector = cv.SimpleBlobDetector_create(params)

您根本不需要 PIL。坚持使用 OpenCV 函数读写图像文件(imread/imwrite)以及灰度转换(cvtColor)。

【讨论】:

  • 这可能是一个错误的论点,但 OpenCV 仍然处理不当 - 它应该产生 TypeError 或其他东西,而不是破坏 Python 函数调用机制。
  • 当然,OpenCV 的 python 绑定有时会出现糟糕的错误消息。随时提交(最小复制示例)作为 OpenCV github 上的问题。
  • @ChristophRackwitz 谢谢你的回答!据我所知,SimpleBlobDetector 似乎勾勒出图像中发现的斑点,但实际上并没有计算它们。你知道是否有办法计算它们,以实际得到一个数字吗?抱歉,如果这无关紧要,我找不到任何相关信息。
  • 您的代码已经包含keypoints = detector.detect(newImg)print(keypoints)。那是blob的列表。每个“关键点”描述一个 blob。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-21
  • 2020-12-13
相关资源
最近更新 更多