为了实现目标精确识别,颜色分割只是其中的一种方法,对于大多数图片,我们还是更倾向于对图片进行高斯模糊去噪的方法,此外网上还有很多其他的方法,这里只介绍我认为好用的这一种。
为什么选取高斯模糊去噪的方法呢?
因为高斯模糊去噪的时候,函数内部的判别阈值可以自行设定,阈值的大小直接影响了去噪的强弱(这里不能说是去噪好坏,因为根据不同图片,想要达到的效果也不同)。有时候匹配的效果不尽人意,修改一下阈值重新运行一遍就好了。
我们这里最终要做的还是要提高模板匹配的精度,使在有干扰的情况下完成模板匹配,所以在降噪的时候为了保持模板和目标内容的同步,需要将模板和目标图片同时进行降噪处理,之后的匹配也会在降噪后的图片之间进行。一言不合就上代码:
def Img_Outline(original_img):
gray_img = cv.cvtColor(original_img, cv.COLOR_BGR2GRAY)
blurred = cv.GaussianBlur(gray_img, (9, 9), 0) # 高斯模糊去噪(设定卷积核大小影响效果)
_, RedThresh = cv.threshold(blurred, 140, 255, cv.THRESH_BINARY) # 设定阈值,对识别很重要,可以手动调节识别效果(阈值影响开闭运算效果)
kernel = cv.getStructuringElement(cv.MORPH_RECT, (5, 5)) # 定义矩形结构元素
closed = cv.morphologyEx(RedThresh, cv.MORPH_CLOSE, kernel) # 闭运算(链接块)
opened = cv.morphologyEx(closed, cv.MORPH_OPEN, kernel) # 开运算(去噪点)
return original_img, gray_img, RedThresh, closed, opened
###原图
tpl ="D://PythonPicTemplate/binarization/tankTemplate3.jpg"
target = "D://PythonPicTemplate/binarization/tanks4.jpg"
tpl = Img_read(tpl)
target = Img_read(target)
red = (0, 0, 255)
green = (0,255,0)
col = red
thickness = 5
methods = []
for o in range(0,num):
methods.append(cv.TM_CCORR_NORMED)
'''''
差值平方和匹配 CV_TM_SQDIFF
标准化差值平方和匹配 CV_TM_SQDIFF_NORMED
相关匹配 CV_TM_CCORR
标准相关匹配 CV_TM_CCORR_NORMED
相关匹配 CV_TM_CCOEFF
标准相关匹配 CV_TM_CCOEFF_NORMED
'''
th, tw = tpl.shape[:2]
rows, cols = target.shape[:2]
content1 = "正在分析模板大小:"
printGreen(content1.decode("utf-8").encode("gbk") )
print "TemplateSize: ",th, tw
content2 = "正在分析目标大小:"
printGreen(content2.decode("utf-8").encode("gbk"))
print "TargetSize: ", rows,cols
i =0
tl0 = []
br0 = []
for md in methods:
result = cv.matchTemplate(target, tpl, md)
min_val, max_val, min_loc, max_loc = cv.minMaxLoc(result)
if md == cv.TM_SQDIFF_NORMED:
tl0.append(min_loc)
else:
tl0.append(max_loc)
br0.append((tl0[i][0]+tw, tl0[i][1]+th))
cv.rectangle(target, tl0[i], br0[i], (0, 0, 255),2)
i += 1
original_img, gray_img, RedThresh, closed, opened = Img_Outline(tpl)
original_imgT, gray_imgT, RedThreshT, closedT, openedT = Img_Outline(dst)
#cv.imshow("original", original_img)
#cv.imshow("gray", gray_img)
#cv.imshow("closed", closed)
cv.namedWindow("opened", cv.WINDOW_NORMAL)
cv.imshow("opened", opened)
#cv.imshow("original", original_imgT)
#cv.imshow("grayT", gray_imgT)
#cv.imshow("closedT", closedT)
cv.namedWindow("openedT", cv.WINDOW_NORMAL)
cv.imshow("openedT", openedT)
结果如下所示:
下一次将使用特定算法对坦克军团特定连线处理,以及生成坦克阵型简图。
代码已上传至GitHub及Gitee,欢迎star,欢迎讨论:
GitHub:https://github.com/wangwei39120157028/Machine_Learning_research_on_simple_target_recognition_and_intention_analysis
Gitee:https://gitee.com/wwy2018/Machine_Learning_research_on_simple_target_recognition_and_intention_analysis/settings