【问题标题】:remove the element attached to the image border删除附加到图像边框的元素
【发布时间】:2021-01-01 22:44:44
【问题描述】:

我正在使用 OpenCV 使用图像处理来检测胸部 X 光中的肺炎,所以我需要删除图像边界的附加区域以仅获取肺部,谁能帮我在 python 中编码?

这张图片解释了我想要什么this image after applying this methods: resized, Histogram Equalization, otsu Thresholded and inverse binary Thresholded, morphological processes(opening then closing)

这是Original Image的原图

【问题讨论】:

  • 对不起,这不是 stackoverflow 的工作方式。请重复How do I ask a good question
  • 您的问题不清楚。请更详细地说明您想要什么。你想让黑色区域透明吗?或者您是否希望将其修剪为白色区域周围的最小边界框。还是您希望每个白色区域分开。我们不知道您所说的“删除”是什么意思!请发布您的代码和原始图像。
  • 我想得到只有白色的肺部区域,并将其他白色区域转换为背景(黑色区域)

标签: python opencv image-processing detection


【解决方案1】:

这就是我在 Python/OpenCV 中解决问题的方法。在四周添加一个白色边框,用黑色填充以替换白色,然后删除多余的边框。

输入:


import cv2
import numpy as np

# read image
img = cv2.imread('lungs.jpg')
h, w = img.shape[:2]

# convert to gray
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# add 1 pixel white border all around
pad = cv2.copyMakeBorder(gray, 1,1,1,1, cv2.BORDER_CONSTANT, value=255)
h, w = pad.shape

# create zeros mask 2 pixels larger in each dimension
mask = np.zeros([h + 2, w + 2], np.uint8)

# floodfill outer white border with black
img_floodfill = cv2.floodFill(pad, mask, (0,0), 0, (5), (0), flags=8)[1]

# remove border
img_floodfill = img_floodfill[1:h-1, 1:w-1]    

# save cropped image
cv2.imwrite('lungs_floodfilled.png',img_floodfill)

# show the images
cv2.imshow("img_floodfill", img_floodfill)
cv2.waitKey(0)
cv2.destroyAllWindows()

【讨论】:

    【解决方案2】:

    您可以尝试使用带有边框的形态重建作为标记。这类似于 Matlab 或 Octave 中的 imclearborder 函数。

    import cv2
    import numpy as np
    img = cv2.imread('5R0Zs.jpg')
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    thresh = cv2.threshold(gray, 40, 255, cv2.THRESH_BINARY)[1]
    kernel = np.ones((7,7),np.uint8)
    kernel2 = np.ones((3,3),np.uint8)
    marker = thresh.copy()
    marker[1:-1,1:-1]=0
    while True:
        tmp=marker.copy()
        marker=cv2.dilate(marker, kernel2)
        marker=cv2.min(thresh, marker)
        difference = cv2.subtract(marker, tmp)
        if cv2.countNonZero(difference) == 0:
            break
    
    mask=cv2.bitwise_not(marker)
    mask_color = cv2.cvtColor(mask, cv2.COLOR_GRAY2BGR)
    out=cv2.bitwise_and(img, mask_color)
    cv2.imwrite('out.png', out)
    cv2.imshow('result', out )
    cv2.waitKey(0) # waits until a key is pressed
    cv2.destroyAllWindows()
    

    【讨论】:

    • 感谢您的回答。你的输出是我想要的,但在我的代码中我有一个错误。如果你愿意,我会向你展示我的完整代码,这就是错误。此语句中的错误:out=cv2.bitwise_and(img, mask_color) TypeError: Expected Ptr<:umat> for argument 'src1'
    • 尝试将第一个参数 img 替换为 gray 或 thresh。 out = cv2.bitwise_and (gray, mask_color) 或 out = cv2.bitwise_and (thresh, mask_color)。这是由于图像中的通道数所致。
    • 还要确保图像 img 是从磁盘读取的。
    猜你喜欢
    • 2015-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-17
    • 2020-03-27
    • 1970-01-01
    相关资源
    最近更新 更多