Python OpenCV 排线线序识别 线序颜色识别
·
转载请注明出处,联系我:田工,15118249062(微信同号)
裁剪区域

正确的模板

得到的结果

# -*- coding: utf-8 -*-
"""
Created on Fri Nov 13 10:54:55 2020
"""
import cv2
import numpy as np
#import math
#2.png为原始图片
img = cv2.imread('2.png')
img2 = cv2.imread('2.png')
#t.png为模板图片
t=cv2.imread('t.png')
#高斯模糊,滤波
img = cv2.GaussianBlur(img, (3, 3),0)
t = cv2.GaussianBlur(t, (3, 3),0)
h1,w1 = img.shape[:2]
h2,w2 = t.shape[:2]
#TM_CCOEFF_NORMED 模板匹配
res = cv2.matchTemplate(img,t,cv2.TM_CCOEFF_NORMED)
threshold = 0.8
loc = np.where( res >= threshold)
n=0
for pt in zip(*loc[::-1]):
cv2.rectangle(img, pt, (pt[0] + w2, pt[1] + h2), (0,0,255), 1)
#n=n+1
#cv2.imshow('img_red',img)
HSV = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
H, S, V = cv2.split(HSV)
LowerBlue = np.array([0, 0, 0])
UpperBlue = np.array([10, 255, 255])
mask = cv2.inRange(HSV, LowerBlue, UpperBlue)
Things = cv2.bitwise_and(img, img, mask=mask)
erode_hsv = cv2.erode(Things, None, iterations=0)
Things=cv2.cvtColor(erode_hsv,cv2.COLOR_RGB2GRAY)
cnts = cv2.findContours(Things.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[-2]
#cv2.drawContours(img,cnts,-1,(0,255,255),3)
#cv2.imshow('img_cnts',img)
#判断每个匹配的cnts
n2=0
for i in range(len(cnts)):
rect = cv2.minAreaRect(cnts[i])
(x, y), radius = cv2.minEnclosingCircle(cnts[i])
radius = int(radius)
#print (rect[1][0]*rect[1][1])
box = cv2.boxPoints(rect)
if rect[1][0]*rect[1][1]>5000:
#print (rect[1][0]*rect[1][1])
cv2.drawContours(img2, [np.int0(box)], -1, (255, 0, 0), 6)
#print(x,y)
#cv2.circle(img,(int(x)+n2*3,int(y)+n2*3),10,(255, 0, 0),6)
"""
if n2%2==1:
cv2.drawContours(img, [np.int0(box)+n2*10], -1, (255, 0, 0), 6)
else:
cv2.drawContours(img, [np.int0(box)+n2*10], -1, (255, 255, 0), 6)
"""
n2=n2+1
#cv2.resize(img,(1600,28),img)
print('right Num is:'+str(n2))
cv2.imshow('img',img2)
cv2.imwrite('res.png',img2)
cv2.waitKey(0)
cv2.destroyAllWindows()

更多推荐


所有评论(0)