Python OpenCV:从RGB图像中提取并保存轮廓
以下是一个Python程序,可以将RGB图像转换为二值图像,并查找并保存所有轮廓图像:\n\npython\nimport cv2\n\ndef convert_to_binary(image):\n # 将RGB图像转换为灰度图像\n gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n # 使用自适应阈值方法将灰度图像转换为二值图像\n _, binary = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)\n return binary\n\ndef find_and_save_contours(binary_image, original_image):\n # 查找二值图像中的所有轮廓\n contours, _ = cv2.findContours(binary_image, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\n # 创建一个空白的黑色图像,用于保存轮廓图像\n contour_image = cv2.cvtColor(binary_image, cv2.COLOR_GRAY2BGR)\n contour_image[:] = (0, 0, 0)\n \n # 遍历所有轮廓\n for contour in contours:\n # 绘制当前轮廓到轮廓图像上\n cv2.drawContours(contour_image, [contour], -1, (255, 255, 255), thickness=cv2.FILLED)\n \n # 将轮廓图像保存到文件\n cv2.imwrite("contour_image.jpg", contour_image)\n\n# 读取RGB图像\nimage = cv2.imread("rgb_image.jpg")\n\n# 将RGB图像转换为二值图像\nbinary_image = convert_to_binary(image)\n\n# 查找并保存所有轮廓图像\nfind_and_save_contours(binary_image, image)\n\n\n请注意,上述代码中的"rgb_image.jpg"应替换为实际的RGB图像文件路径。程序将生成一个名为contour_image.jpg的文件,其中包含所有轮廓的图像。
原文地址: https://www.cveoy.top/t/topic/qiJ2 著作权归作者所有。请勿转载和采集!