python opencv图片二值化后取出图片中心区域的轮廓
1.导入必要的库:
import cv2
import numpy as np
2.读取图片并将其转为灰度图像:
image = cv2.imread('image.jpg')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
3.对灰度图像进行二值化处理:
ret, thresh = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)
4.找到轮廓并筛选出中心区域的轮廓:
# 使用 cv2.findContours() 找到图像的轮廓
contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
center_contours = []
# 对于每一个轮廓,使用 cv2.moments() 计算矩
for contour in contours:
M = cv2.moments(contour)
# 使用 M["m00"] 访问第 0 阶矩
# 使用 M["m10"] 访问第 1 阶矩
# 使用 M["m01"] 访问第 2 阶矩
# 以此类推
if M['m00'] > 0:
cX = int(M['m10'] / M['m00'])
cY = int(M['m01'] / M['m00'])
# 计算中心轮廓
if cX > 0.25 * image.shape[1] and cX < 0.75 * image.shape[1] and cY > 0.25 * image.shape[0] and cY < 0.75 * image.shape[0]:
center_contours.append(contour)
5.在原始图像上绘制中心区域的轮廓:
cv2.drawContours(image, center_contours, -1, (0, 255, 0), 3)
这里将轮廓绘制为绿色。
6.显示结果:
cv2.imshow("Contours", image)
cv2.waitKey(0)
cv2.destroyAllWindows()