Python OpenCV 图像轮廓检测与保存
下面是一个使用 OpenCV 库在 Python 中编写的程序,用于查找图像中的所有轮廓并保存。
import cv2
def find_and_save_contours(image_path, output_path):
# 读取图像
image = cv2.imread(image_path)
# 将图像转换为灰度图像
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# 进行阈值处理
ret, thresh = cv2.threshold(gray, 127, 255, 0)
# 查找轮廓
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# 绘制轮廓
image_with_contours = cv2.drawContours(image, contours, -1, (0, 255, 0), 3)
# 保存带有轮廓的图像
cv2.imwrite(output_path, image_with_contours)
# 显示图像
cv2.imshow('Contours', image_with_contours)
cv2.waitKey(0)
cv2.destroyAllWindows()
# 示例用法
image_path = 'input_image.jpg'
output_path = 'output_image.jpg'
find_and_save_contours(image_path, output_path)
请确保在运行程序之前已经安装了 OpenCV 库。在示例中,image_path 变量指定输入图像的路径,output_path 变量指定保存带有轮廓的图像的路径。运行程序后,它将显示包含所有轮廓的图像,并将保存该图像到指定路径。
原文地址: https://www.cveoy.top/t/topic/qiJQ 著作权归作者所有。请勿转载和采集!