實(shí)戰(zhàn) | OpenCV如何將不同輪廓合并成一個(gè)輪廓(附源碼)
導(dǎo)讀
本文主要介紹如何用OpenCV將不同的輪廓合并成一個(gè)輪廓的實(shí)現(xiàn)方法和代碼演示。
背景介紹
在圖像處理的應(yīng)用場景中常常會(huì)遇到一種情況,本來是一個(gè)整體的目標(biāo),因?yàn)椴煌牧炼然蚱渌驅(qū)е滤指畛啥鄠€(gè)部分,這種情況在用OpenCV處理的時(shí)候會(huì)被當(dāng)成多個(gè)輪廓(如下圖所示),那么遇到這種情況,我們?nèi)绾伟巡煌妮喞喜⒊梢粋€(gè)輪廓,然后做后續(xù)的處理呢?
實(shí)現(xiàn)方法與步驟
這里我們不用上面的繪畫圖,而是使用下面這張圖做演示:
我們的目的:將上圖中的文字輪廓看成一個(gè)整體,然后求其最小外接矩形,獲得角度,將文字旋轉(zhuǎn)水平,后續(xù)可以做簡單的文字識(shí)別。
【1】先提取文字部分輪廓(S通道閾值處理)
hsvImg = cv2.cvtColor(src,cv2.COLOR_BGR2HSV)
H,S,V = cv2.split(hsvImg)
ret, thresImg= cv2.threshold(S, 138, 255, cv2.THRESH_BINARY)
hsvImg = cv2.cvtColor(src,cv2.COLOR_BGR2HSV) H,S,V = cv2.split(hsvImg) ret, thresImg= cv2.threshold(S, 138, 255, cv2.THRESH_BINARY)
【2】中值濾波去除小雜訊
blurImg = cv2.medianBlur(thresImg,5)
cv2.imshow('blur', blurImg)
【3】查找輪廓計(jì)算輪廓最小外接矩形
contours,hierarchy = cv2.findContours(blurImg, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
merge_list = []
for cnt in contours:
rect = cv2.minAreaRect(cnt)
box = cv2.boxPoints(rect)
box = np.int0(box)
split_res = cv2.drawContours(split_res,[box],0,(0,0,255),2)
merge_list.append(cnt)
hsvImg = cv2.cvtColor(src,cv2.COLOR_BGR2HSV) H,S,V = cv2.split(hsvImg) ret, thresImg= cv2.threshold(S, 138, 255, cv2.THRESH_BINARY)
【4】輪廓合并成一個(gè)繪制最小外接矩形
contours_merge = np.vstack([merge_list[0],merge_list[1]])
for i in range(2, len(merge_list)):
contours_merge = np.vstack([contours_merge,merge_list[i]])
rect2 = cv2.minAreaRect(contours_merge)
box2 = cv2.boxPoints(rect2)
box2 = np.int0(box2)
merge_res = cv2.drawContours(merge_res,[box2],0,(0,255,0),2)
完整代碼與效果:
import numpy as np
import cv2
src = cv2.imread('A.jpg')
cv2.imshow('src', src)
split_res = src.copy()#顯示每個(gè)輪廓結(jié)構(gòu)
merge_res = src.copy()#顯示合并后輪廓結(jié)構(gòu)
# 記錄開始時(shí)間
start = cv2.getTickCount()
hsvImg = cv2.cvtColor(src,cv2.COLOR_BGR2HSV)
H,S,V = cv2.split(hsvImg)
ret, thresImg= cv2.threshold(S, 138, 255, cv2.THRESH_BINARY)
cv2.imshow('threshold', thresImg)
blurImg = cv2.medianBlur(thresImg,5)
cv2.imshow('blur', blurImg)
contours,hierarchy = cv2.findContours(blurImg, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
merge_list = []
for cnt in contours:
rect = cv2.minAreaRect(cnt)
box = cv2.boxPoints(rect)
box = np.int0(box)
split_res = cv2.drawContours(split_res,[box],0,(0,0,255),2)
merge_list.append(cnt)
cv2.imshow('split_res', split_res)
cv2.imwrite('split_res.jpg', split_res)
contours_merge = np.vstack([merge_list[0],merge_list[1]])
for i in range(2, len(merge_list)):
contours_merge = np.vstack([contours_merge,merge_list[i]])
rect2 = cv2.minAreaRect(contours_merge)
box2 = cv2.boxPoints(rect2)
box2 = np.int0(box2)
merge_res = cv2.drawContours(merge_res,[box2],0,(0,255,0),2)
cv2.imshow('merge_res', merge_res)
cv2.imwrite('merge_res.jpg', merge_res)
# 記錄結(jié)束時(shí)間
end = cv2.getTickCount()
# 運(yùn)行耗時(shí)
use_time = (end - start) / cv2.getTickFrequency()
print('use-time: %.3fs' % use_time)
cv2.waitKey(0)
cv2.destroyAllWindows()
print ('finish')