python - 如何使用 Python OpenCV 查找图像中的极端外部点

标签 python image opencv image-processing computer-vision

我有这张雕像的图片。

enter image description here

我正在尝试找到雕像的顶部、底部、左侧和右侧的大部分点。有没有办法测量每边的边缘以确定雕像上最外面的点?我想获取每边的 (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()

最佳答案

这是一个可能的方法:


转为灰度图并进行模糊处理后,我们进行阈值处理得到二值图像

现在我们使用 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/

相关文章:

css - 使用 CSS 为图像添加彩色条

c++ - OpenCV 边界模式与模糊滤镜的问题

python - 在 OpenCV python 中测量点到掩码的距离

Python 多处理不能很好地与 uuid.uuid4() 配合使用

python - 如何根据该行的第 1 列与该行的第 2 列相比大多少来给出某些行 'points'

java - 如何读取包含文本和图像数据的文件?

image - 按颜色组织图像

opencv - 如何获取相机立体校正后的投影矩阵?

python - 为什么 Python 中的整数需要三倍的内存?

Python - trml2pdf 生成空白 PDF