要使用 OpenCV 2 来识别图像中的红色边框并保存为新图片,可以按照以下步骤进行操作:\n\n1. 导入必要的库和模块:\n\npython\nimport cv2\nimport numpy as np\n\n\n2. 加载图像并将其转换为 HSV 颜色空间:\n\npython\nimage = cv2.imread('image.jpg') # 替换为你的图像文件路径\nhsv_image = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)\n\n\n3. 定义红色的 HSV 范围:\n\npython\nlower_red = np.array([0, 100, 100])\nupper_red = np.array([10, 255, 255])\n\n\n4. 根据红色的 HSV 范围创建掩码:\n\npython\nred_mask = cv2.inRange(hsv_image, lower_red, upper_red)\n\n\n5. 对掩码进行形态学处理以去除噪声:\n\npython\nkernel = np.ones((5, 5), np.uint8)\nred_mask = cv2.morphologyEx(red_mask, cv2.MORPH_OPEN, kernel)\n\n\n6. 在图像上找到红色边框的轮廓:\n\npython\ncontours, hierarchy = cv2.findContours(red_mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\n\n\n7. 找到最大的轮廓并绘制边框:\n\npython\nmax_contour = max(contours, key=cv2.contourArea)\nx, y, w, h = cv2.boundingRect(max_contour)\ncv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2)\n\n\n8. 保存带有红色边框的新图片:\n\npython\ncv2.imwrite('image_with_red_border.jpg', image)\n\n\n完整的代码如下:\n\npython\nimport cv2\nimport numpy as np\n\nimage = cv2.imread('image.jpg') # 替换为你的图像文件路径\nhsv_image = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)\n\nlower_red = np.array([0, 100, 100])\nupper_red = np.array([10, 255, 255])\n\nred_mask = cv2.inRange(hsv_image, lower_red, upper_red)\n\nkernel = np.ones((5, 5), np.uint8)\nred_mask = cv2.morphologyEx(red_mask, cv2.MORPH_OPEN, kernel)\n\ncontours, hierarchy = cv2.findContours(red_mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\n\nmax_contour = max(contours, key=cv2.contourArea)\nx, y, w, h = cv2.boundingRect(max_contour)\ncv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2)\n\ncv2.imwrite('image_with_red_border.jpg', image)\n\n\n在运行代码之前,请确保已经安装了 OpenCV 库并将图像文件替换为你要处理的实际图像路径。运行后,将在当前目录下生成名为“image_with_red_border.jpg”的新图片,其中包含了红色边框。

使用 OpenCV2 识别图像中的红色边框并另存为新图片

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

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