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