想要做一个色块重复色检查工具,
但是现在图片中不是所有的色块都能够被识别和标记
代码是AI写的,不知道怎么优化
# 导入模块
import cv2
import numpy as np
import matplotlib.pyplot as plt
# 读取图片并转换为RGB格式
img = cv2.imread("image.png")
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
# 转换为灰度图并二值化
gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
_, thresh = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)
# 检测轮廓并绘制
contours, _ = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
cv2.drawContours(img, contours, -1, (0, 0, 255), 3)
# 计算轮廓的中心点和颜色的HCV值
centers = []
colors = []
for c in contours:
# 计算轮廓的矩和中心点坐标
M = cv2.moments(c)
cx = int(M["m10"] / M["m00"])
cy = int(M["m01"] / M["m00"])
centers.append((cx, cy))
# 获取中心点坐标对应的像素值,并转换为HSV格式
pixel = img[cy][cx]
pixel_hsv = cv2.cvtColor(np.array([[pixel]]), cv2.COLOR_RGB2HSV)[0][0]
colors.append(pixel_hsv)
# 比较颜色的HCV值,如果相同则用红色线连接中心点
for i in range(len(colors)):
for j in range(i + 1, len(colors)):
# 设置颜色相似度阈值,根据需要调整
threshold = 1
# 如果颜色的HCV值都在阈值范围内,则认为是相同颜色,并绘制红色线段连接中心点
if abs(colors[i][0] - colors[j][0]) < threshold and abs(colors[i][1] - colors[j][1]) < threshold and abs(colors[i][2] - colors[j][2]) < threshold:
cv2.line(img, centers[i], centers[j], (255, 0 ,0), 3)
# 显示图片并自动适配屏幕尺寸
plt.figure(figsize=(10 * img.shape[1] / img.shape[0], 10))
plt.imshow(img)
plt.axis("off")
plt.show()
因为它用的是蓝色,你看61下面的几行。
虽然colors里装的是每个色块的颜色[黑,黑,浅蓝],centers里装的是每个色块的中心点[黑中心点A,黑的中心点B,浅蓝对应的中心点C]。
它判断A、B对应的颜色相同,然后它就让两个黑色块的中心画蓝色圈圈,并用蓝色连接这两个中心。
会不会是黑色里面画蓝色你看不出来啊,你可以改成黄色或明亮的不会被黑色吃掉的颜色试下