python - 如何使用 OpenCV Python 检测对象的边缘点?
问题描述
所以,我已经检测到了一个对象的所有边缘,但问题是我找不到每个边缘的两个点,即起点和终点及其坐标。
实际上我试图找到一个物体的测量值,但我被这个问题困住了。图像与图像的 ROI 有关。
import cv2
import numpy as np
from matplotlib import pyplot as plt
#Read Image of the Object
img = cv2.imread("C:\\Users\\Desktop\\Project\\captured.jpg")
cv2.imshow('Original Image', img)
cv2.waitKey(0)
#Convert Image To GrayScale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
cv2.imshow('Gray', gray)
cv2.waitKey(0)
#Binary Thresholding
ret, thresh = cv2.threshold(gray, 150, 255, cv2.THRESH_BINARY_INV)
cv2.imshow('Binary Image', thresh)
cv2.waitKey(0)
#Crop Image
cropped = thresh[150:640, 150:500]
cv2.imshow('Cropped Image', cropped)
cv2.waitKey(0)
#Edge Detection
edges = cv2.Canny(cropped, 100, 200)
cv2.imshow('Edges', edges)
cv2.waitKey(0)
#find contours
ctrs, hier = cv2.findContours(cropped, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
#Sort Contours
sorted_ctrs = sorted(ctrs, key=lambda ctr: cv2.boundingRect(ctr)[0] + cv2.boundingRect(ctr)[1] * cropped.shape[1])
#ROI
for i, ctr in enumerate(sorted_ctrs):
# Get bounding box
x, y, w, h = cv2.boundingRect(ctr)
# Getting ROI
roi = cropped[y:y + h, x:x + w]
# show ROI
# cv2.imshow('segment no:'+str(i),roi)
cv2.rectangle(cropped , (x, y), (x + w, y + h), (150, 0, 255), 2)
cv2.imshow('marked areas', cropped)
cv2.waitKey(0)
解决方案
尝试改用Harris 角点检测:
import cv2
import numpy as np
def find_centroids(dst):
ret, dst = cv2.threshold(dst, 0.01 * dst.max(), 255, 0)
dst = np.uint8(dst)
# find centroids
ret, labels, stats, centroids = cv2.connectedComponentsWithStats(dst)
# define the criteria to stop and refine the corners
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 100,
0.001)
corners = cv2.cornerSubPix(gray,np.float32(centroids),(5,5),
(-1,-1),criteria)
return corners
image = cv2.imread("corner.jpg")
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
gray = np.float32(gray)
dst = cv2.cornerHarris(gray, 2, 3, 0.04)
dst = cv2.dilate(dst, None)
# Threshold for an optimal value, it may vary depending on the image.
# image[dst > 0.01*dst.max()] = [0, 0, 255]
# Get coordinates
corners= find_centroids(dst)
# To draw the corners
for corner in corners:
image[int(corner[1]), int(corner[0])] = [0, 0, 255]
cv2.imshow('dst', image)
cv2.waitKey(0)
cv2.destroyAllWindows()
结果:
您可能需要微调cornerHarris 的参数。
推荐阅读
- javascript - 在 jquery 中显示 TempData 消息
- c# - 如何在静态方法中定义和引发事件(PropertyChangedCallback)
- javascript - v-if 在我的子组件中不起作用
- python - 如果其他两列在 Pandas 中有匹配的值,如何用另一个数据框的值填充空列值?
- rust - 如何即时从 hyper::Response 解压缩 XZ 数据?
- java - 无法写入外部存储
- chisel - 使用 SyncReadMem 时 Vivado 无法识别双端口 RAM
- python - Spyder/Python - 自动将工作目录设置为当前脚本的
- node.js - 使用 bodyparser 在多行上创建 Postgres 更新
- db2 - 在 DB2 的一行中显示列值