步驟簡述
使用OpenCV繪製矩形輪廓框,一般包括如下步驟:
- 轉換爲灰度圖;
- 進行閾值處理;
- 進行中值濾波;
- 在原始圖像上繪製矩形框。
附圖解析
原始圖像:
第一步,轉換爲灰度圖:
第二步,經過閾值處理:
第三步,中值濾波後:
最後一步,在原始圖像上繪製矩形框:
生成的記錄文件(矩形輪廓框四個端點的平面座標)
1: [367,201 367,210 371,201 371,210] 2: [362,195 362,197 363,195 363,197] 3: [297,187 297,190 301,187 301,190] 4: [396,182 396,184 398,182 398,184] 5: [371,168 371,190 394,168 394,190] 6: [382,166 382,169 387,166 387,169] 7: [211,160 211,189 238,160 238,189] 8: [377,148 377,163 402,148 402,163] 9: [308,148 308,217 353,148 353,217] 10: [315,193 315,215 348,193 348,215] 11: [277,148 277,188 311,148 311,188] 12: [241,147 241,190 274,147 274,190] 13: [179,132 179,189 235,132 235,189] 14: [355,129 355,192 372,129 372,192]
Code
附上自己寫的實驗代碼:
# coding=utf-8 import cv2 # 原圖像路徑 origin_pic = cv2.imread('./origin.jpg') # 文檔路徑,用於記錄輪廓框座標 txt_file = open('./contours.txt', 'w') # 要先轉換成單通道灰度圖像才能進行後續的圖像處理 pic = cv2.cvtColor(origin_pic, cv2.COLOR_BGR2GRAY) # 閾值處理,將前景全填充爲白色,背景全填充爲黑色 _, pic = cv2.threshold(src=pic, thresh=200, maxval=255, type=1) # 中值濾波,去除椒鹽噪聲 pic = cv2.medianBlur(pic, 5) # 邊緣檢測,得到的輪廓列表 _1, contours, _2 = cv2.findContours(pic, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) # 根據輪廓列表,循環在原始圖像上繪製矩形邊界 for i in range(len(contours)): cnt = contours[i] x, y, w, h = cv2.boundingRect(cnt) origin_pic = cv2.rectangle(origin_pic, (x, y), (x+w, y+h), (255, 0, 0), 2) txt_file.write('{}: [{},{} {},{} {},{} {},{}]\n'.format(i+1, x, y, x, y+h, x+w, y, x+w, y+h)) cv2.imwrite('./rectangle.jpg', origin_pic) txt_file.close() cv2.imshow('', origin_pic) cv2.waitKey(0) cv2.destroyAllWindows()