python opencv 画出二值化图片轮廓具体代码
时间: 2023-03-08 14:20:29 浏览: 62
使用OpenCV函数cv2.threshold()可以实现二值化图片轮廓,具体代码如下:import cv2
image = cv2.imread('image.jpg')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
ret, thresh = cv2.threshold(gray, 10, 255, cv2.THRESH_BINARY)
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
cv2.drawContours(image, contours, -1, (0, 255, 0), 3)
相关问题
python opencv 画出二值化图片百分之一的轮廓点具体代码
可以使用以下代码来画出二值化图片百分之一的轮廓点:import cv2 img = cv2.imread('input.png', 0)
ret, thresh = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)
contours, hierarchy = cv2.findContours(thresh, 1, 2) # loop over the contours
for c in contours:
# compute the center of the contour
M = cv2.moments(c)
cX = int(M["m10"] / M["m00"])
cY = int(M["m01"] / M["m00"])
# draw the contour and center of the shape on the image
cv2.drawContours(img, [c], -1, (0, 255, 0), 1)
cv2.circle(img, (cX, cY), 1, (255, 255, 255), -1) # show the image
cv2.imshow('image', img)
cv2.waitKey(0)
python opencv 画出二值化图片百分之一的轮廓点轮廓具体代码
### 回答1:
可以使用以下代码:# 加载图片
image = cv2.imread('image.jpg')
# 转换为灰度图
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# 使用Otsu法计算二值化阈值
threshold, _ = cv2.threshold(gray_image, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)
# 使用计算的阈值进行二值化
binary_image = cv2.threshold(gray_image, threshold, 255, cv2.THRESH_BINARY)[1]
# 计算图像的轮廓
contours, _ = cv2.findContours(binary_image, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# 仅取轮廓点的1%
contours_1_percent = contours[::len(contours)//100]
# 画出轮廓点
cv2.drawContours(image, contours_1_percent, -1, (0,255,0), 3)
### 回答2:
import cv2
# 读取原始图片
image = cv2.imread('image.jpg', 0)
# 对图像进行二值化处理
_, binary_image = cv2.threshold(image, 127, 255, cv2.THRESH_BINARY)
# 寻找二值化图像的轮廓
contours, hierarchy = cv2.findContours(binary_image, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
# 计算需要绘制的轮廓点的数量
total_points = int(len(contours[0]) * 0.01)
# 创建一个空白的黑色图像,与原始图像大小相同
contour_image = np.zeros_like(image)
# 绘制轮廓点
cv2.drawContours(contour_image, contours, 0, (255, 255, 255), total_points)
# 展示结果图像
cv2.imshow('Contour Image', contour_image)
cv2.waitKey(0)
cv2.destroyAllWindows()