pythonimport cv2import numpy as npimport matplotlib.pyplot as plt# 1. 环境验证(可选)print("OpenCV版本:", cv2.__version__)# 2. 读取图像(替换为自己的图像路径)img = cv2.imread("feature_test.jpg")if img is None:print("错误:未找到图像,请检查图像路径!")else:img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)img_blur = cv2.GaussianBlur(img_gray, (3, 3), sigmaX=1)# 3. 提取4大核心特征# 3.1 边缘特征(Canny)edges = cv2.Canny(img_blur, 50, 150)# 3.2 颜色特征(红色)lower_red = np.array([150, 0, 0])upper_red = np.array([255, 100, 100])red_mask = cv2.inRange(img_rgb, lower_red, upper_red)# 3.3 形状特征(轮廓+面积+周长)contours, _ = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)img_shape = cv2.cvtColor(img_gray, cv2.COLOR_GRAY2BGR)for i, contour in enumerate(contours):cv2.drawContours(img_shape, [contour], -1, (0, 255, 0), 2)area = cv2.contourArea(contour)perimeter = cv2.arcLength(contour, True)cv2.putText(img_shape, f"Area:{int(area)}", (10, 30+i*30), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 255, 0), 2)# 3.4 纹理特征(水平方向Sobel)texture = cv2.Sobel(img_blur, cv2.CV_64F, 1, 0, ksize=3)texture = cv2.normalize(texture, None, 0, 255, cv2.NORM_MINMAX, dtype=cv2.CV_8U)# 4. 综合特征应用(边缘+颜色+形状)lower_blue = np.array([0, 0, 150])upper_blue = np.array([100, 100, 255])blue_mask = cv2.inRange(img_rgb, lower_blue, upper_blue)combined_mask = cv2.bitwise_and(edges, blue_mask)contours_combined, _ = cv2.findContours(combined_mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)img_combined = img.copy()for contour in contours_combined:cv2.drawContours(img_combined, [contour], -1, (0, 0, 255), 2)area = cv2.contourArea(contour)perimeter = cv2.arcLength(contour, True)x, y = contour[0][0]cv2.putText(img_combined, f"Area:{int(area)}", (x, y-30), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 0, 255), 2)# 5. 统一显示所有效果plt.figure(figsize=(15, 10))# 第一行:4大核心特征plt.subplot(2, 4, 1)plt.imshow(img_rgb)plt.title("原始图像")plt.axis("off")plt.subplot(2, 4, 2)plt.imshow(edges, cmap="gray")plt.title("边缘特征")plt.axis("off")plt.subplot(2, 4, 3)plt.imshow(red_mask, cmap="gray")plt.title("颜色特征(红色)")plt.axis("off")plt.subplot(2, 4, 4)plt.imshow(img_shape)plt.title("形状特征(面积)")plt.axis("off")# 第二行:纹理特征+综合应用plt.subplot(2, 4, 5)plt.imshow(texture, cmap="gray")plt.title("纹理特征")plt.axis("off")plt.subplot(2, 4, 6)plt.imshow(blue_mask, cmap="gray")plt.title("颜色特征(蓝色)")plt.axis("off")plt.subplot(2, 4, 7)plt.imshow(combined_mask, cmap="gray")plt.title("边缘+颜色综合掩码")plt.axis("off")plt.subplot(2, 4, 8)plt.imshow(cv2.cvtColor(img_combined, cv2.COLOR_BGR2RGB))plt.title("综合特征应用结果")plt.axis("off")plt.tight_layout()plt.show()# 6. 保存结果(可选)cv2.imwrite("edge_feature.jpg", edges)cv2.imwrite("color_feature.jpg", red_mask)cv2.imwrite("shape_feature.jpg", img_shape)cv2.imwrite("combined_feature.jpg", img_combined) |