我目前正在嘗試實施一篇閱讀壓力表的論文。有一個步驟我不知道該怎么做。它說:“然后旋轉顯示輪廓以垂直對齊橢圓的長軸,并內接在用于裁剪儀表影像的矩形中。” 所以我不確定如何垂直旋轉這個影像,為了更好地理解,我將向您展示當前影像是什么以及它需要什么的示例。

我目前在步驟C,需要在步驟D的位置獲取影像。示例中的文本檢測目前并不重要。
目前我有正確的輪廓和橢圓來顯示。
(cnts, boundingBoxes) = sort_contours(cnts)
#find correct contours and fitellipse
if len(cnts) != 0:
for i in range(len(cnts)):
if len(cnts[i]) >= 5: #if contours has more than 5 points
# cv2.drawContours(image,cnts[0],-1,(150,10,255),3)
ellipse = cv2.fitEllipse(cnts[i])
finalElps.append(ellipse) #(centx,centy), (width,height), angle
for i in range(len(finalElps)):
centx = finalElps[i][0][0]
centy = finalElps[i][0][1]
eWidth = finalElps[i][1][0]
eHeight = finalElps[i][1][1]
sfRes = Sf(eWidth, eHeight)
cfRes = Cf(centx, imgCenterX, centy, imgCenterY)
afRes = Af(eWidth,eHeight,imgWidth,imgHeight)
print("SF: " str(sfRes) "| " "CF: " str(cfRes) "| Af: " str(afRes))
if(sfRes < 0.4 and cfRes < 6 and afRes < 0.9):
print(finalElps[i])
cv2.ellipse(image, finalElps[i], (255,0,0), 2)
plt.imshow(image)
sfRes、cfRes 和 afRes 只是為了找到正確的橢圓而進行的計算。
我下一步應該做什么才能達到垂直旋轉?我認為它的正確名稱是“影像校正”,但我不是 100% 確定它
uj5u.com熱心網友回復:
以下是如何從影像 C 中獲取影像 D:
- 找到二進制掩碼

- 找到一個橢圓(中心、寬度、高度、角度)

- 在橢圓的對邊找到 4 個點

- 使用這 4 個點來獲得可用于將旋轉的儀表影像扭曲為矩形影像的透視變換。最終結果:

代碼:
import cv2
import numpy as np
image = cv2.imread("gauge.png")
# find the parameters of the ellipse
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
mask = cv2.threshold(gray, 10, 255, cv2.THRESH_BINARY)[1]
points = np.stack(np.nonzero(mask.T)).T
hull = cv2.convexHull(points)
(cx, cy), (width, height), angle = cv2.fitEllipse(hull)
# for visualization
# cv2.ellipse(image, (int(cx), int(cy)), (int(width/2), int(height/2)), angle, 0, 360, (0, 0, 255), 2)
# find the points on the opposite sides of the ellipse
# define rectangular homogenuous coordinates and rotate them using a rotation matrix
mat = cv2.getRotationMatrix2D((cx, cy), -angle, 1)
mat = np.vstack((mat, [0, 0, 1]))
coords = np.array(
[
[cx width // 2, cy, 1],
[cx - width // 2, cy, 1],
[cx, cy height // 2, 1],
[cx, cy - height // 2, 1],
]
)
points = (mat @ coords.T)[:2].T # drop the homogenuos part
# for visualization
# for px, py in points.astype(int)[:2]:
# cv2.circle(image, (px, py), 10, (0, 0, 255), -1)
# for px, py in points.astype(int)[2:]:
# cv2.circle(image, (px, py), 10, (255, 0, 0), -1)
# define points on the target image to which the ellipse points should be mapped
size = 300
target = np.float32(
[
[size, size // 2],
[0, size // 2],
[size // 2, size],
[size // 2, 0],
]
)
mat = cv2.getPerspectiveTransform(points.astype(np.float32), target)
rect_image = cv2.warpPerspective(image, mat, (size, size))
cv2.imwrite("rect_gauge.png", rect_image)
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/519700.html
