記錄一些可能有用的圖像處理方法,包括源輪廓、近似輪廓、凸包、直邊外接矩形、最小外接矩形、擬合直線。
上述操作都是基於圖像灰度圖:
import cv2
import numpy as np
img = cv2.imread('./test.png')
imgray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret, thresh = cv2.threshold(imgray, 127, 255, cv2.THRESH_BINARY)
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
Rect_x = []
Rect_area = []
for cnt in contours:
# 源輪廓
cv2.drawContours(img, [cnt], -1, (0, 255, 0), 2)
# 近似多邊形, 輪廓近似,是Douglas-Peucker算法的一種實現方式
# epsilon 爲近似度參數,該值需要輪廓的周長信息
# 多邊形周長與源輪廓周長之比就是epsilon
epsilon = 0.01 * cv2.arcLength(cnt,True)
approx = cv2.approxPolyDP(cnt, epsilon, True)
cv2.drawContours(img, [approx], -1, (255, 255, 0), 2)
# 凸包
hull = cv2.convexHull(cnt)
cv2.drawContours(img, [hull], -1, (0, 0, 255), 2)
#直邊外接矩形
x,y,w,h = cv2.boundingRect(cnt)
area = w*h
# 這裏可以限制外接矩形大小,如果太小就不畫出來。
if w*h>200:
print('x,y:', 'x', ',', 'y')
Rect_x.append((x,y,w,h))
Rect_area.append(area)
cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,0),2)
# 最小外接矩形
rect = cv2.minAreaRect(cnt)
box = cv2.boxPoints(rect)
box = np.int0(box)
print(box)
cv2.drawContours(img,[box],0,(0,0,255),2)
# cv2.imwrite('./test_rect.png', img)
# 擬合直線,這個還沒有試過
# rows,cols = img.shape[:2]
# [vx,vy,x,y] = cv2.fitLine(cnt, cv2.DIST_L2,0,0.01,0.01)
# lefty = int((-x*vy/vx) + y)
# righty = int(((cols-x)*vy/vx)+y)
# cv2.line(img,(cols-1,righty),(0,lefty),(0,255,0),2)
cv2.imshow("test_image",img)
cv2.waitKey(0)
cv2.destroyAllWindows()