完善color_detect()函数,增加蓝色、绿色和紫色的识别:

def color_detect(self, img):
    # set the arrangement of color'HSV
    x = y = 0
    for mycolor, item in self.HSV.items():
        # get the lower and upper bounds of the color range
        lower = np.array(item[0])
        upper = np.array(item[1])
        # transform the image to HSV color space
        hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
        # create a mask to isolate the color range
        mask = cv2.inRange(hsv, lower, upper)
        # apply morphological operations to the mask to remove noise and smooth edges
        kernel = np.ones((5, 5), np.uint8)
        opening = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel)
        closing = cv2.morphologyEx(opening, cv2.MORPH_CLOSE, kernel)
        # find contours in the mask
        contours, hierarchy = cv2.findContours(closing, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

        if len(contours) > 0:
            # filter out small contours and non-square contours
            boxes = [cv2.boundingRect(c) for c in contours if cv2.contourArea(c) > 100 and abs(cv2.minAreaRect(c)[1][0] - cv2.minAreaRect(c)[1][1]) < 20]
            if boxes:
                # get the largest contour
                c = max(contours, key=cv2.contourArea)
                # get the bounding box of the contour
                x, y, w, h = cv2.boundingRect(c)
                # draw a rectangle around the contour
                cv2.rectangle(img, (x, y), (x+w, y+h), (0, 255, 0), 2)
                # calculate the center of the rectangle
                x, y = x + w//2, y + h//2
                # set the color of the cube
                if mycolor == "yellow":
                    self.color = 1
                elif mycolor == "red":
                    self.color = 0
                elif mycolor == "green":
                    self.color = 2
                elif mycolor == "blue":
                    self.color = 3
                elif mycolor == "purple":
                    self.color = 4

    if abs(x) + abs(y) > 0:
        return x, y
    else:
        return None

在这个函数中,我们首先遍历了所有的颜色范围,然后对于每个颜色,我们使用cv2.inRange()函数创建一个掩膜,将图像中不在颜色范围内的像素设置为0,而在颜色范围内的像素设置为255。接着,我们对掩膜应用形态学操作,包括开运算和闭运算,以去除噪声和平滑边缘。然后,我们找到掩膜中的所有轮廓,并筛选出面积大于100且近似为正方形的轮廓。接着,我们找到最大的轮廓,并获取其边界框。最后,我们计算边界框的中心,并为检测到的方块设置颜色。如果没有检测到方块,则返回None

完善color_detect现在只能是被黄色和红色能够实现蓝色绿色紫色class Detect_markerobject def __init__self superDetect_marker self__init__ selfmc = MyCobotusb_dev baudrate selfmcpower_on selfyolo =

原文地址: http://www.cveoy.top/t/topic/egLX 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录