我正在将图像预处理到我的新计算机视觉模型。我一直在尝试找到从图像中删除小物体的最佳解决方案,但没有一个有效。
首先,我决定删除宽度或高度小于 80 且大于 400 的对象。它对某些图像有效,但该解决方案不够通用。现在我想删除大于 400 的对象,然后删除面积小于最大和最小面积差值 25% 的对象。不知怎的,它不起作用。感觉它没有标记那些非常小的区域:
label_image = morphology.label(filled_image)
filtered_image = np.copy(filled_image)
regions = measure.regionprops(label_image)
for region in regions:
if region.solidity < 0.85:
filtered_image_statistic[label_image == region.label] = 0
max_size = 400
if region.bbox[2] - region.bbox[0] > max_size or region.bbox[3] - region.bbox[1] > max_size:
filtered_image_statistic[label_image == region.label] = 0
min_row, min_col, max_row, max_col = region.bbox
if min_row < 10 or min_col < 10 or max_row > image_height - 10 or max_col > image_width - 10:
filtered_image_statistic[label_image == region.label] = 0
labeled_image = morphology.label(filtered_image)
regions = measure.regionprops(labeled_image)
regions_areas = [region.area for region in regions]
test = max(regions_areas) - min(regions_areas)
print(f"{test}, {max(regions_areas)}, {min(regions_areas)}")
for region in regions:
print(region.area)
if region.area <= 0.25*test:
filtered_image_statistic[labeled_image == region.label] = 0
show_image(filtered_image_statistic)
import cv2
import numpy as np
from skimage import morphology
def remove_small_objects(image, min_size):
# Convert the image to grayscale
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# Threshold the image (you may need to adjust the threshold value)
_, binary = cv2.threshold(gray, 128, 255, cv2.THRESH_BINARY)
# Remove small objects using morphological operations
binary = morphology.remove_small_objects(binary, min_size)
# Apply inverse threshold
binary = cv2.bitwise_not(binary)
# Apply the mask to the original image
result = cv2.bitwise_and(image, image, mask=binary)
return result
# Load your image
image = cv2.imread('your_image.jpg')
# Define the minimum size of objects to keep
min_size = 100 # Adjust this value based on your needs
# Remove small objects
result_image = remove_small_objects(image, min_size)
# Save the result
cv2.imwrite('result_image.jpg', result_image)