opencv 我试图从Spring的图像中获取区域长度和宽度,当我运行代码时,它给予我多个对象,并绘制多个边界框

zfycwa2u  于 2023-06-30  发布在  Spring
关注(0)|答案(1)|浏览(112)

我试图从Spring的照片中得到尺寸。我附上了我从光学比较仪得到的Spring图像。当我运行代码并打印出area的结果时,它给了我大约八到九个其他对象的面积,所以我添加了边界框,Spring由一堆较小的边界框组成。我不知道如果我不理解的概念层次结构的什么,但我有好看的图像灰度,然后到阈值和精明的边缘发现者,所以我不知道我错过了什么在这里。我也试着在其他图像上运行代码,它做了同样的事情,它在单个对象周围给予了多个边界框。让我知道你的想法

import cv2
import numpy as np

# Read Image
img = cv2.imread("springNpng.png")
imgGray = cv2.cvtColor(img, cv2.IMREAD_GRAYSCALE)
ret, thresh = cv2.threshold(imgGray, 170, 255, cv2.THRESH_BINARY)
edged = cv2.Canny(thresh, 30, 200)

contours, heirarchy = cv2.findContours(edged, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

cv2.drawContours(img, contours, -1, (0,255,0), 2)

#cnt = contours
#M = cv2.moments(cnt)
for cnt in contours:
    area = cv2.contourArea(cnt)
    print(area)
    (x, y, w, h) = cv2.boundingRect(cnt)
    cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 3)

cv2.imshow("img", img)
cv2.imshow("edged", edged)
cv2.waitKey(0)

光学比较仪的压缩Spring:

rta7y2nd

rta7y2nd1#

这里有一种在Python/OpenCV中解决问题的方法。

  • 读取输入
  • 转换为灰度
  • 阈值
  • 可选形态学关闭和/或打开,以删除离群值
  • 反转阈值
  • 将阈值图像转换为点
  • 得到点的船体
  • 得到船体的旋转矩形及其参数
  • 在输入的副本上绘制船体和旋转矩形
  • 保存船体和旋转的rect图像

输入:

import cv2
import numpy as np

# read the input
img = cv2.imread('spring.png')
print(img.shape)

# convert to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# threshold 
thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU)[1]

# invert
thresh = 255 - thresh

# convert to points
points = np.column_stack(np.where(thresh.transpose() > 0))

# get convex hull
hull = cv2.convexHull(points)

# get rotated rectangle
rect = cv2.minAreaRect(hull)

# get parameters of rect
(center), (width,height), angle = rect

# correct angle
if angle < -45:
    angle = (90 + angle)
else:
    angle = angle

print('width:', width, 'height:', height, 'angle:', angle)

# draw convex hull and rotated rect on copy of input
outline = img.copy()
cv2.polylines(outline, [hull], True, (0,0,255), 2)
box = np.intp(cv2.boxPoints(rect))
cv2.polylines(outline, [box], True, (0,255,0), 2)

# save outline image
cv2.imwrite('spring_outline.png', outline)

# show outline image
cv2.imshow('outline', outline)
cv2.waitKey(0)

输入上的船体和旋转矩形(红色是凸包,绿色是旋转矩形)

旋转矩形参数:

width: 505.5112609863281 height: 160.70016479492188 angle: 2.929425001144409

相关问题