我有如下格式化的图像:测试用例
我希望能够检测出有多少“岩石”,以及它们代表多少个像素。我尝试使用开放式 cv,但它总是勾勒出岩石以外的其他东西。有没有更适合这个的实现?
我已尝试过:
import cv2
import numpy as np
import matplotlib.pyplot as plt
image_path = "medium.png"
original_image = cv2.imread(image_path)
gray_image = cv2.cvtColor(original_image, cv2.COLOR_BGR2GRAY)
binary_image = cv2.adaptiveThreshold(gray_image, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
cv2.THRESH_BINARY_INV, 11, 2)
_, binary_image2 = cv2.threshold(gray_image, 230, 255, cv2.THRESH_BINARY_INV)
combined_binary = cv2.bitwise_or(binary_image, binary_image2)
kernel = np.ones((2, 2), np.uint8)
cleaned_binary = cv2.morphologyEx(combined_binary, cv2.MORPH_OPEN, kernel, iterations=1)
contours, _ = cv2.findContours(cleaned_binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
output_image = np.ones_like(original_image) * 255
np.random.seed(42)
hues = np.linspace(0, 179, len(contours), dtype=np.uint8)
np.random.shuffle(hues)
colors = []
for hue in hues:
hsv = np.array([[[hue, 255, 255]]], dtype=np.uint8)
rgb = cv2.cvtColor(hsv, cv2.COLOR_HSV2BGR)[0][0]
colors.append(rgb.tolist())
min_area_threshold = 10
valid_particles = 0
for i, contour in enumerate(contours):
area = cv2.contourArea(contour)
if area >= min_area_threshold:
valid_particles += 1
cv2.drawContours(output_image, [contour], -1, colors[i % len(colors)], -1)
cv2.drawContours(output_image, [contour], -1, (0, 0, 0), 1)
cv2.imwrite('binary_image.png', binary_image)
cv2.imwrite('binary_image2.png', binary_image2)
cv2.imwrite('combined_binary.png', combined_binary)
cv2.imwrite('cleaned_binary.png', cleaned_binary)
plt.figure(figsize=(12, 10))
plt.imshow(cv2.cvtColor(output_image, cv2.COLOR_BGR2RGB))
plt.title(f'Total Particles Detected: {valid_particles}')
plt.axis('off')
plt.tight_layout()
plt.show()
print(f"Total number of actual particles detected: {valid_particles}")
cv2.imwrite('colored_particles_improved.png', output_image)
但我仍然留下了如下图所示的块我的预处理
有没有办法更好地分离块?