python - 使用 Python OpenCV 查找图像中的极端外部点
问题描述
我有这个雕像的图像。
我试图在雕像上找到顶部、底部、左侧和右侧的点。有没有办法测量每边的边缘以确定雕像上的最外点?我想得到(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 数组对图像进行编码,因此轮廓只是一个 Numpy(x,y)
坐标数组。我们可以对 Numpy 数组进行切片并使用argmin()
orargmax()
来确定外部的左、右、顶和底坐标,如下所示
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])
这是结果
左:(162、527)
右:(463、467)
顶部: (250, 8)
底部:(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()
推荐阅读
- google-chrome - 禁用 Internet 访问以测试 ionic 应用程序,但仍从 localhost 提供文件
- kubernetes - iam ConfirmSubscription 权限错误
- odbc - 在 Windows 10 上找不到 Lotus Notes ODBC
- reactjs - 我们可以在一个组件中有多个 useEffect 挂钩吗
- c# - 您可以使用原始 graphQL 语法使用 octokit.net 库在 c# 中查询 github API v4 吗?
- asp.net - 受保护的异步子程序未在生产中执行
- bash - sed 在模式中保留通配符值
- mysql - mysql xdevapi nodejs:返回插入的行 auto_increment id
- python - Tkinter在Anaconda Windows10中只能导入运行一次
- pdf - PDF:混淆文本编码以防止自动解析和复制+粘贴