我有这张雕像的图片。
我正在尝试找到雕像的顶部、底部、左侧和右侧的大部分点。有没有办法测量每边的边缘以确定雕像上最外面的点?我想获取每边的 (x,y)
坐标。我尝试使用 cv2.findContours()
和 cv2.drawContours()
来绘制雕像的轮廓。
import cv2
img = cv2.imread('statue.png')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
contours = cv2.findContours(gray, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)[0]
cv2.drawContours(img, contours, -1, (0, 200, 0), 3)
cv2.imshow('img', img)
cv2.waitKey()
最佳答案
这是一个可能的方法:
将图像转换为 grayscale 和 Gaussian blur
Threshold 获取二值图像
获取外坐标
转为灰度图并进行模糊处理后,我们进行阈值处理得到二值图像
现在我们使用 cv2.findContours()
找到轮廓。由于 OpenCV 使用 Numpy 数组对图像进行编码,因此轮廓只是 (x,y)
坐标的 Numpy 数组。我们可以切片 Numpy 数组并使用 argmin()
或 argmax()
像这样确定外左、右、上、下坐标
left = tuple(c[c[:, :, 0].argmin()][0])
right = tuple(c[c[:, :, 0].argmax()][0])
top = tuple(c[c[:, :, 1].argmin()][0])
bottom = tuple(c[c[:, :, 1].argmax()][0])
这是结果
left: (162, 527)
right: (463, 467)
top: (250, 8)
bottom: (381, 580)
import cv2
import numpy as np
# Load image, grayscale, Gaussian blur, threshold
image = cv2.imread('1.png')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (3,3), 0)
thresh = cv2.threshold(blur, 220, 255, cv2.THRESH_BINARY_INV)[1]
# Find contours
cnts = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
c = max(cnts, key=cv2.contourArea)
# Obtain outer coordinates
left = tuple(c[c[:, :, 0].argmin()][0])
right = tuple(c[c[:, :, 0].argmax()][0])
top = tuple(c[c[:, :, 1].argmin()][0])
bottom = tuple(c[c[:, :, 1].argmax()][0])
# Draw dots onto image
cv2.drawContours(image, [c], -1, (36, 255, 12), 2)
cv2.circle(image, left, 8, (0, 50, 255), -1)
cv2.circle(image, right, 8, (0, 255, 255), -1)
cv2.circle(image, top, 8, (255, 50, 0), -1)
cv2.circle(image, bottom, 8, (255, 255, 0), -1)
print('left: {}'.format(left))
print('right: {}'.format(right))
print('top: {}'.format(top))
print('bottom: {}'.format(bottom))
cv2.imshow('thresh', thresh)
cv2.imshow('image', image)
cv2.waitKey()
关于python - 如何使用 Python OpenCV 查找图像中的极端外部点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56781635/