1 读取图片
2 检查图片是否读取成功
3 将图片转换为灰度图像
4 对灰度图像进行二值化处理
5 查找轮廓
6 创建一个与原图同样大小的全白图像
7 在全白图像上绘制所有轮廓,轮廓颜色为红色
8 显示原图和带有轮廓的图像
9 将轮廓坐标点打印出来并保存到.txt文件中。
10 关闭窗口
代码:
import cv2
import numpy as np
import os
# 读取图片
img_path = 'C:/Users/lizhi/Desktop/tupian/tu6.jpg' # 替换为你的图片路径
img = cv2.imread(img_path)
# 检查图片是否读取成功
if img is None:
print("错误:图片未正确读取,请检查文件路径。")
exit()
# 将图片转换为灰度图像
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 对灰度图像进行二值化处理
ret, img_binary = cv2.threshold(gray, 125, 255, cv2.THRESH_BINARY)
# 查找轮廓
contours, hierarchy = cv2.findContours(img_binary, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
# 创建一个与原图同样大小的全白图像
img_contours = np.zeros(img.shape, np.uint8) + 255
# 在全白图像上绘制所有轮廓,轮廓颜色为红色
cv2.drawContours(img_contours, contours, -1, (0, 0, 255), 2)
# 显示原图和带有轮廓的图像
cv2.imshow('原图', img)
cv2.imshow('轮廓', img_contours)
if (os.path.isfile("test.txt")):
os.remove("test.txt")
for cnt in contours:
for point in cnt:
x,y = point[0];
with open("test.txt", 'a') as f:
f.write(str(x)+'\t' +str(y)+'\n')
print(x,y)
"""
# 遍历所有轮廓,并计算它们的矩
for n, contour in enumerate(contours):
moments = cv2.moments(contour)
# 打印轮廓的矩
print(f'轮廓{n}的矩:', moments)
# 打印轮廓的面积,注意:如果m00为0,则不计算面积
if moments['m00'] != 0:
area = moments['m00']
print(f'轮廓{n}的面积:', area)
else:
print(f'轮廓{n}没有有效面积。')
"""
# 等待按键,然后关闭窗口
cv2.waitKey(0)
cv2.destroyAllWindows()
结果: