效果图如下:
原图:
完整代码:
import cv2
import numpy as np
from skimage import measure
import random
image = cv2.imread('113.jpg', cv2.IMREAD_GRAYSCALE)
blurred_img = cv2.GaussianBlur(image, (5, 5), 0)
_, binary_image = cv2.threshold(blurred_img, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)
kernel = np.ones((3, 3), np.uint8)
img2 = cv2.morphologyEx(binary_image, cv2.MORPH_OPEN, kernel, iterations=2)
labels = measure.label(img2, connectivity=2, background=0)
props = measure.regionprops(labels)
output_image = cv2.cvtColor(image, cv2.COLOR_GRAY2BGR)
colors = []
for _ in range(len(props)):
colors.append((random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)))
chromosome_count = len(props)
chromosome_sizes = []
for i, prop in enumerate(props):
y, x = prop.centroid
center = (int(x), int(y))
cv2.circle(output_image, center, 5, colors[i], -1)
cv2.putText(output_image, f'{i+1}', (center[0] + 10, center[1]), cv2.FONT_HERSHEY_SIMPLEX, 0.5, colors[i], 1)
chromosome_sizes.append(prop.area)
print(f"染色体数量: {chromosome_count}")
print(f"每个染色体的尺寸(像素数量): {chromosome_sizes}")
cv2.imshow('img2', img2)
cv2.imshow('output_image', output_image)
cv2.waitKey(0)
cv2.destroyAllWindows()