0

## 讓畫面中的矩形依照特定順序排列的問題?

https://codepen.io/samdrivert/pen/mdJbaqL

marlin12 iT邦研究生 5 級 ‧ 2020-02-05 21:15:23 檢舉

Rotation-Invariant Pattern Recognition Approach
Using Extracted Descriptive Symmetrical Patterns

https://pdfs.semanticscholar.org/8618/0f3bbb08a9068d3bf0babae718de51c75751.pdf?_ga=2.215927828.20661267.1580907238-1398463595.1580907238

### 1 個回答

0
marlin12
iT邦研究生 5 級 ‧ 2020-02-06 22:07:40

``````import cv2
import numpy as np
import imutils
from matplotlib import pyplot as plt

# convert to gray
img_gray = cv2.cvtColor( img_org, cv2.COLOR_BGR2GRAY )

# remove noise
img_smooth = cv2.GaussianBlur( img_gray, (11, 11), 0 )

# thresholding

# find contours
contours, _ = cv2.findContours( img_thres, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE )

# find contour with maximum area
maxarea = 50
for contour in contours:
epsilon = 0.1 * cv2.arcLength( contour, True )
poly_approx = cv2.approxPolyDP( contour, epsilon, True )
area = cv2.contourArea( poly_approx )
if area > maxarea:
maxarea = area
contour_max = poly_approx

# draw the contour
img_contour = img_org.copy()
cv2.drawContours( img_contour, [contour_max], 0, (255, 0, 0), 3 )

# correct contour orientation
(x, y), (w, h), angle = cv2.minAreaRect( contour_max )

rot_angle = (90 + angle) if angle < -45 else angle
print( rot_angle, "deg" )

img_correct = imutils.rotate( img_contour, rot_angle )

# show images
plt.subplot( 2, 2, 1 )
plt.imshow( img_gray, 'gray' )
plt.xticks([]), plt.yticks([])

plt.subplot( 2, 2, 2 )
plt.imshow( img_thres, 'gray' )
plt.xticks([]), plt.yticks([])

plt.subplot( 2, 2, 3 )
plt.imshow( img_contour )
plt.xticks([]), plt.yticks([])

plt.subplot( 2, 2, 4 )
plt.imshow( img_correct )
plt.xticks([]), plt.yticks([])

plt.show()

cv2.waitKey( 0 )
cv2.destroyAllWindows()
``````