如何使用Python删除图像中的小对象 [英] How to remove small object in image with Python

查看:47
本文介绍了如何使用Python删除图像中的小对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的python代码有问题.我想用胸部X射线进行图像处理以获得肺部图案.但是我的代码结果仍然很少有污点.如何摆脱这些小物体

i have a problem with my python code. I want to make image processing with chest X-rays in order to obtain a lung pattern. but my code results still have little stains. how to get rid of these small objects

这是我的代码

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)

P.S:当我尝试使用matlab代码时,可以使用此代码删除小对象

P.S : when i try with the matlab code, the small object can be removed with this code

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

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

and that code can remove small object well:

推荐答案

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

You can filter using contour area then apply morpholgical closing to fill the small holes in the image. Here's the result:

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删除图像中的小对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆