请写出python opencv 为二值化图片轮廓点每一百个取一个样点,并获取样点坐标的具体代码
时间: 2023-03-08 14:16:40 浏览: 53
import cv2
import numpy as np# 读取图片
img = cv2.imread("image.jpg")# 将图片转化为灰度图像
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)# 进行二值化处理
ret, binary = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)# 提取轮廓
contours, hierarchy = cv2.findContours(binary,
cv2.RETR_EXTERNAL,
cv2.CHAIN_APPROX_NONE)# 取出轮廓点,每一百个取一个样点,并获取样点坐标
step = int(len(contours[0])/100)
sample_points = []
for i in range(100):
sample_points.append(contours[0][i*step])# 转化为numpy数组
sample_points = np.array(sample_points)# 获取样点坐标
x_coords = list(sample_points[:,:,0].flatten())
y_coords = list(sample_points[:,:,1].flatten())
相关问题
请写出python opencv 找出二值化图片百分之一的轮廓点坐标的具体代码
import cv2
import numpy as np # 读取图片
img = cv2.imread('image.png', 0) # 获取图片二值化
ret, thresh = cv2.threshold(img, 127, 255, 0) # 找到轮廓
contours, hierarchy = cv2.findContours(thresh, 1, 2) # 获取轮廓百分之一的坐标点
contour_points = contours[0][::int(len(contours[0])/100)] # 打印坐标
for point in contour_points:
print(point[0])
请写出python opencv 画出二值化图片百分之一的轮廓点具体代码
### 回答1:
import cv2
import numpy as np
# 读取图片
img = cv2.imread('binary_image.jpg')
# 灰度化
grayImage = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 二值化
ret,thresh = cv2.threshold(grayImage,127,255,cv2.THRESH_BINARY)
# 轮廓检测
image, contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
# 画出轮廓点,百分之一
sample_contour = np.vstack([contours[i] for i in range(0,len(contours),int(len(contours)/100))])
# 画图
cv2.drawContours(img, [sample_contour], 0, (0,255,0), 3)
# 显示
cv2.imshow('img', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
### 回答2:
以下是使用Python和OpenCV画出二值化图片百分之一的轮廓点的代码:
```python
import cv2
import numpy as np
# 读取二值化图像
image = cv2.imread("binary_image.png", 0)
# 检测轮廓
contours, _ = cv2.findContours(image, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# 计算百分之一的轮廓点数目
total_points = sum(len(contour) for contour in contours)
points_threshold = int(0.01 * total_points)
# 画出百分之一的轮廓点
for contour in contours:
# 如果轮廓点数小于阈值,则忽略该轮廓
if len(contour) < points_threshold:
continue
# 随机选择颜色
color = np.random.randint(0, 255, size=3).tolist()
# 画出轮廓点
for point in contour:
x, y = point[0]
cv2.circle(image, (x, y), 1, color, -1)
# 显示画出轮廓点的图像
cv2.imshow("Contour Points", image)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
请注意,在代码中的`"binary_image.png"`处需要替换为实际的二值化图像的文件路径。此代码会读取二值化图像,找到轮廓,计算出百分之一的轮廓点数目,然后随机选择颜色,在原始图像上画出百分之一的轮廓点,并显示结果图像。
### 回答3:
import cv2
# 读取图片
image = cv2.imread("image.jpg", 0)
# 进行二值化处理
_, binary = cv2.threshold(image, 127, 255, cv2.THRESH_BINARY)
# 查找轮廓
contours, _ = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# 计算轮廓点数量
contour_count = len(contours[0])
# 获取所需数量的轮廓点
sample_count = int(contour_count * 0.01)
sample_points = contours[0][:sample_count]
# 绘制轮廓点
for point in sample_points:
x, y = point[0]
cv2.circle(image, (x, y), 1, (255, 0, 0), -1)
# 显示结果
cv2.imshow("Contours", image)
cv2.waitKey(0)
cv2.destroyAllWindows()