import cv2 import numpy as np class FindConTours: def __init__(self, path): self.img = cv2.imread(path) self.box_list = [] def common_contours(self): img = self.img hsv_image = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) Bch, Gch, Rch = cv2.split(hsv_image) _, Gch = cv2.threshold(Gch, 155, 255, cv2.THRESH_BINARY) kernel = cv2.getStructuringElement(1, (5, 5)) Gch = cv2.erode(Gch, kernel, iterations=1) kernel = cv2.getStructuringElement(1, (5, 5)) Gch = cv2.dilate(Gch, kernel, iterations=1) cv2.imshow('dilate', Gch) cv2.waitKey(0) contours, hierarchy = cv2.findContours(Gch, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) for c in contours: area = cv2.contourArea(c) if area < 3000: continue x, y, w, h = cv2.boundingRect(c) # 计算点集最外面的矩形边界 self.box_list.append([x, y, w, h]) def find_blue(self): img = self.img lower = np.array([101, 43, 46]) upper = np.array([112, 255, 255]) hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) mask = cv2.inRange(hsv, lower, upper) s = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5)) openI = cv2.morphologyEx(mask, cv2.MORPH_OPEN, s, iterations=1) closeI = cv2.morphologyEx(openI, cv2.MORPH_CLOSE, s, iterations=1) contours, hierarchy = cv2.findContours(closeI, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) cv2.imshow("closeI", closeI) cv2.waitKey(0) for c in contours: area = cv2.contourArea(c) if area < 800: continue x, y, w, h = cv2.boundingRect(c) # 计算点集最外面的矩形边界 self.box_list.append([x, y, w, h, "blue"]) def identify_colors(self): sorted(self.box_list, key=lambda x: x[0]) print(self.box_list) img = self.img color_dist = {'red': {'Lower': np.array([156, 43, 46]), 'Upper': np.array([180, 255, 255])}, 'yellow': {'Lower': np.array([20, 43, 46]), 'Upper': np.array([25, 255, 255])}, 'green': {'Lower': np.array([50, 50, 50]), 'Upper': np.array([130, 255, 255])}, } for box in self.box_list: if len(box) == 5: continue x, y, w, h = box[:4] roi = img[y:y + h, x:x + w] hsv = cv2.cvtColor(roi, cv2.COLOR_BGR2HSV) for key in color_dist: if len(box) == 5: continue lower_range = color_dist[key]['Lower'] upper_range = color_dist[key]['Upper'] mask = cv2.inRange(hsv, lower_range, upper_range) pixel_count = cv2.countNonZero(mask) total_pixels = w * h white_pixel_ratio = pixel_count / total_pixels if white_pixel_ratio > 0.2: box.append(key) def draw_text(self): img = self.img for box in self.box_list: x, y, w, h = box[:4] cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2) if len(box) == 5: text = box[4] else: text = None text_size, _ = cv2.getTextSize(text, cv2.FONT_HERSHEY_SIMPLEX, 1, 2) text_x = x + int((w - text_size[0]) / 2) text_y = y + int((h + text_size[1]) / 2) cv2.putText(img, text, (text_x, text_y), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2) find_contours = FindConTours("img_2.png") find_contours.common_contours() find_contours.find_blue() find_contours.identify_colors() find_contours.draw_text() cv2.imshow("Image", find_contours.img) cv2.waitKey(0)