gpt4 book ai didi

python - 如何用Python去除图像中的小物体

转载 作者:行者123 更新时间:2023-12-02 10:18:51 30 4
gpt4 key购买 nike

我的 python 代码有问题。我想对胸部X光片进行图像处理以获得肺部模式。但我的代码结果仍然有一点污点。如何摆脱这些小物体

enter image description here

这是我的代码

import cv2
import numpy as np
from skimage import morphology

im = cv2.imread('image.jpg')
ret, thresh = cv2.threshold(im, 150, 255, cv2.THRESH_BINARY)
kernel = np.ones((5, 5), np.uint8)
opening = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel)
cleaned = morphology.remove_small_objects(opening, min_size=62, connectivity=2)
cv2.imshow("cleaned", cleaned)
cv2.waitKey(0)

附:当我尝试使用 matlab 代码时,可以使用此代码删除小物体

K=bwareaopen(~K,1500); %Remove small object (area) pixels less than 1500 pixels

该代码可以很好地删除小对象:

enter image description here

最佳答案

您可以使用轮廓区域进行过滤,然后应用形态学闭合来填充图像中的小孔。结果如下:

enter image description here

import cv2

# Load image, convert to grayscale, Gaussian blur, Otsu's threshold
image = cv2.imread('1.jpg')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (3,3), 0)
thresh = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]

# Filter using contour area and remove small noise
cnts = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
for c in cnts:
area = cv2.contourArea(c)
if area < 5500:
cv2.drawContours(thresh, [c], -1, (0,0,0), -1)

# Morph close and invert image
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5,5))
close = 255 - cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel, iterations=2)

cv2.imshow('thresh', thresh)
cv2.imshow('close', close)
cv2.waitKey()

关于python - 如何用Python去除图像中的小物体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60033274/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com