import cv2 import numpy as np def test(): raw = cv2.imread("./data/003.png") # 设定颜色HSV范围,假定为红色 redLower = np.array([30, 0, 0]) redUpper = np.array([255, 193, 255]) img = raw # 将图像转化为HSV格式 hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) # 去除颜色范围外的其余颜色 mask = cv2.inRange(hsv, redLower, redUpper) cv2.imshow("mask", mask) # 二值化操作 ret, binary = cv2.threshold(mask, 0, 255, cv2.THRESH_BINARY) # 膨胀操作,因为是对线条进行提取定位,所以腐蚀可能会造成更大间隔的断点,将线条切断,因此仅做膨胀操作 kernel = np.ones((5, 5), np.uint8) dilation = cv2.dilate(binary, kernel, iterations=1) # # img2 = cv2.bitwise_and(img, img, mask=mask) # cv2.imshow('image', mask) # cv2.waitKey(0) # cv2.destroyAllWindows() # 获取图像轮廓坐标,其中contours为坐标值,此处只检测外形轮廓 contours, hierarchy = cv2.findContours(dilation, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) aim_box = (0, 0, 0, 0) if len(contours) > 0: print('Run!') # cv2.boundingRect()返回轮廓矩阵的坐标值,四个值为x, y, w, h, 其中x, y为左上角坐标,w,h为矩阵的宽和高 boxes = [cv2.boundingRect(c) for c in contours] for box in boxes: x, y, w, h = box if box[2] * box[3] > aim_box[2] * aim_box[3]: aim_box = box # print(box) else: pass # x, y, w, h = aim_box # gray = cv2.GaussianBlur(raw, (5, 5), 0) # canny = cv2.Canny(gray, 70, 210) # contours, hierarchy = cv2.findContours(canny.copy(), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE) # contours = sorted(contours, key=cv2.contourArea, reverse=True)[:3] # # drawed = cv2.drawContours(raw, contours, -1, (0, 0, 255), 2) # print(f"轮廓数量:{len(contours)}") # cv2.imshow("raw", cv2.imread("./data/003.png")) # cv2.imshow("test1", drawed) # cv2.imshow("test", canny) cv2.waitKey(0) # Press the green button in the gutter to run the script. if __name__ == '__main__': test() # See PyCharm help at https://www.jetbrains.com/help/pycharm/