項目實戰-提取手寫數字圖片樣本¶
概要¶
在連通域的外接矩形這篇文章里,阿凱通過MinAreaRect
函數獲取到了帶旋轉的數字區域.
本章阿凱介紹了圖像變換的操作,利用這些操作,我們就可以將此矩形區域提取出來,并提取出統一尺寸的二值化圖像.
keywords 外界矩形 縮放 提取
提取最小外接矩形區域¶
我們可以根據minAreaRect
函數返回的數據結構, 以矩形中心(cx, cy)
作為對原來圖像旋轉的中心點,旋轉角度設定為theta
# 聲明旋轉矩陣 rotateMatrix = cv2.getRotationMatrix2D((cx, cy), theta, 1.0) # 獲取旋轉后的圖像 rotatedImg = cv2.warpAffine(img, rotateMatrix, (img.shape[1], img.shape[0]))
''' 利用minAreaRect繪制最小面積矩形并繪制 ''' import numpy as np import cv2 # 讀入黑背景下的彩色手寫數字 img = cv2.imread("color_number_handwriting.png") # 轉換為gray灰度圖 gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # 尋找輪廓 bimg, contours, hier = cv2.findContours(gray, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) for cidx,cnt in enumerate(contours): minAreaRect = cv2.minAreaRect(cnt) # 轉換為整數點集坐標 # rectCnt = np.int64(cv2.boxPoints(minAreaRect)) ((cx, cy), (w, h), theta) = minAreaRect cx = int(cx) cy = int(cy) w = int(w) h = int(h) # 獲取旋轉矩陣 rotateMatrix = cv2.getRotationMatrix2D((cx, cy), theta, 1.0) rotatedImg = cv2.warpAffine(img, rotateMatrix, (img.shape[1], img.shape[0])) pt1 = (int(cx - w/2), int(cy - h/2)) pt2 = (int(cx + w/2), int(cy + h/2)) # 原圖繪制矩形區域 cv2.rectangle(rotatedImg, pt1=pt1, pt2=pt2,color=(255, 255, 255), thickness=3) # 繪制中心點 cv2.circle(rotatedImg, (cx, cy), 5, color=(255, 0, 0), thickness=-1) cv2.imwrite("minarearect_cidx_{}.png".format(cidx), rotatedImg)
數字樣本圖像轉換為統一尺寸¶
我們截取了包含數字的外接矩形, 他們形狀各異。(可能需要手動旋轉)
如果是制作神經網絡所需要的樣本圖片的話, 我們就需要將其放縮到統一大小。
接下來我們將圖片統一變換到 15*25
并轉換為二值化圖像。
import numpy as np import cv2 from glob import glob img_paths = glob('./number_raw/*.png') # 新的維度為10×20 new_dimension = (15, 25) for img_path in img_paths: # 讀入灰度圖 img = cv2.imread(img_path,cv2.IMREAD_GRAYSCALE) img_name = img_path.split('/')[-1] # 縮放 resized = cv2.resize(img, new_dimension) # 二值化圖片 ret,thresh = cv2.threshold(resized,10,255,0) cv2.imwrite('./number_bin/'+img_name,thresh)