当前位置:网站首页>Learning about opencv (3)
Learning about opencv (3)
2022-07-26 10:11:00 【SingleDog_ seven】
This time, I will study contour detection and template matching , Because of some problems , It takes a lot of time .( It may be the problem of image selection )
Contour detection :
mode: Contour retrieval mode RETR_EXTERNAL: Retrieve only the outermost contour RETR_LIST: Retrieve all the contours , And save it in a linked list RETR_CCOMP: Retrieve all the contours , And organize them into two layers : The top layer is the outer boundary of each part , The second layer is the boundary of the void RETR_TREE: Check all contours , And reconstruct the entire hierarchy of nested profiles method Contour approximation method CHAIN_APPROX_NONE: With Freeman Chain code output outline , All other methods output polygons ( The sequence of vertices ) CHAIN_APPROX_SIMPLE: Compressed horizontal , The vertical and oblique parts , Functions keep only the end part of them
The first step is to introduce images :( For higher accuracy , Use binary images )
img=cv2.imread('people.jpg')
print(img.shape)
gray=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
ret,thresh = cv2.threshold(gray,127,255,cv2.THRESH_BINARY)
print(thresh.shape)
binary,contours,hierarchy=cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE)
Next, draw the border :
# Pass in the drawing image , outline , Outline index , Color mode , Line thickness
# Be careful copy, Or the original picture will change
draw_ = img.copy()
res=cv2.drawContours(img,contours,-1,(0,0,255),2) #2 Represents the line width ,-1 Represent all
cv_show('b',res)
res =cv2.drawContours(draw_,contours,0,(0,0,255),2)
cv_show('c',res)
# Contour feature
cnt = contours[0]
# area
s=cv2.contourArea(cnt)
# Perimeter ,Ture It means closed
c=cv2.arcLength(cnt,True)
# The outline is approximate :
epsilon = 0.1*cv2.arcLength(cnt,True) # You can also set it yourself , Usually the percentage of installation perimeter
approx = cv2.approxPolyDP(cnt,epsilon,True)
drwaContours( Images , Outline index ,-1( Represents the whole outline , Other numbers represent the corresponding contour ), Color , The thickness of the line )
This is the complete code of the outline :
img=cv2.imread('people.jpg')
gray=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
ret,thresh = cv2.threshold(gray,127,255,cv2.THRESH_BINARY)
binary,contours,hierarchy=cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE)
cnt = contours[0]
s=cv2.contourArea(cnt)
c=cv2.arcLength(cnt,True)
draw_ = img.copy()
res=cv2.drawContours(img,[cnt],-1,(0,0,255),2)
# Approximate image contour
epsilon = 0.1*c
approx = cv2.approxPolyDP(cnt,epsilon,True)
draw_ = img.copy()
res=cv2.drawContours(draw_,[approx],-1,(0,0,255),2)
Border rectangle :
Frame the contour on the basis of contour detection :
# Border rectangle
img=cv2.imread('people.jpg')
gray=cv2.cvtColor(img,cv2.COLOR_BGR2RGBA)
ret,thresh = cv2.threshold(gray,127,255,cv2.THRESH_BINARY)
cnt = contours[0]
x,y,w,h=cv2.boundingRect(cnt) #B G R
img=cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,0),2) #2 Represents the line width
cv_show('e',img)

Ratio of contour area to boundary rectangle :( At present, it is not clear what use it has )
rect_ =w * h
area = cv2.contourArea(cnt)
extent = float(area)/rect_ # Ratio of contour area to boundary rectangle
print(extent)Learning outline cv2.findContours(img.mode,method) Errors are always reported here , Some versions have two values , There are three values , It took me a long time to solve this problem .
Next is template matching , Single matching has always had problems in the display of results ( Multiple matches can be used instead of a single match )
TM_SQDIFF: The square is different , The smaller the calculated value is , The more relevant TM_CCORR: Calculate correlation , The larger the calculated value , The more relevant TM_CCOEFF: Calculate the correlation coefficient , The larger the calculated value , The more relevant Normalization is more reliable TM_SQDIFF_NORMED : Calculating the normalized square is different , The closer the calculated value is to 0, The more relevant TM_CCORR_NORMED : Calculate the normalized correlation , The closer the calculated value is to 1, The more relevant TM_CCOEFF_NORMED: Calculate the normalized correlation coefficient , The closer the calculated value is to 1, The more relevant
altogether 6 function , Below 3 This function is more reliable .
methods =['cv2.TM_SQDIFF','cv2.TM_CCORR','cv2.TM_CCOEFF','cv2.TM_SQDIFF_NORMED','cv2.TM_CCORR_NORMED','cv2.TM_CCOEFF_NORMED']
img = cv2.imread('people.jpg',0)
print(img.shape)
img1 = cv2.imread('people1.jpg',0)
cv_show('a',img1)
print(img1.shape)
for meth in methods:
img2=img.copy()
method=eval(meth)
print(method)
res=cv2.matchTemplate(img,img1,method) # Small value
cv_show('a',res)
print(res.shape) # result =A-a+1,B-b+1
min_val ,max_val , min_joc,max_joc= cv2.minMaxLoc(res)
# minimum value , Maximum , Minimum coordinate position , Maximum coordinate position
#cv2.TM_SQDIFF cv2.TM_SQDIFF_NORMED Minimum value
if method in [cv2.TM_SQDIFF,cv2.TM_SQDIFF_NORMED]:
top = min_joc
else:
top = max_joc
tmp = cv2.imread('people1.jpg')
h, w = tmp.shape[:2]
bottom = (top[0]+w,top[1]+h)
print('bottom')
print(bottom)
# Draw a rectangular
cv2.rectangle(img1,top,bottom,255,2)
plt.subplots(221) # The first parameter represents the number of rows in the subgraph ; The second parameter represents the number of columns in the row of images ; The third parameter represents the number of images in each row .
plt.imshow(res,cmap='gray')
plt.xticks([]),plt.yticks([])# Hide axis
plt.subplots(222)
plt.imshow(img2,cmap='gray')
plt.xticks([]),plt.yticks([])
plt.suptitle(meth)
plt.show()
This is going to be 6 Put the functions together , You can observe their differences .( I don't know why there has been a problem here , So I will replace a single match with multiple matches )
img = cv2.imread('people.jpg')
gary=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
tmp = cv2.imread('people1.jpg')
h,w=tmp.shape[:2]
res =cv2.matchTemplate(img,tmp,cv2.TM_CCOEFF_NORMED)
threshold =0.8
loc =np.where(res>=threshold)
for pt in zip(*loc[::-1]): #* Represents an optional parameter
bottom =(pt[0]+w,pt[1]+h)
cv2.rectangle(img,pt,bottom,(0,0,255),2)
cv2.imshow('sss',img)
cv2.waitKey(0)
Next, I continue to look for the cause of the problem ,( It is also possible to match only multiple results ) Complete the goals set for yourself in the summer vacation at your own pace .

边栏推荐
- Wechat H5 payment on WAP, for non wechat browsers
- 论文笔记(SESSION-BASED RECOMMENDATIONS WITHRECURRENT NEURAL NETWORKS)
- 云原生(三十六) | Kubernetes篇之Harbor入门和安装
- Getting started with SQL - combined tables
- Uniapp error 7 < Map >: marker ID should be a number
- 在同一conda环境下先装Pytroch后装TensorFlow
- Encapsulation of tabbarcontroller
- 数通基础-二层交换原理
- B站这个视频我是跪着看完的
- Yarn 'TSC' is not an internal or external command, nor is it a runnable program or batch file. The problem that the command cannot be found after installing the global package
猜你喜欢

Keeping alive to realize MySQL automatic failover

Map key not configured and uniapp routing configuration and jump are reported by the uniapp < map >< /map > component

2021 windows penetration of "Cyberspace Security" B module of Shandong secondary vocational group (analysis)

Alibaba cloud technology expert haochendong: cloud observability - problem discovery and positioning practice

Introduction to latex, EPS picture bounding box

Uniapp error 7 < Map >: marker ID should be a number

AR model in MATLAB for short-term traffic flow prediction

Flask框架初学-04-flask蓝图及代码抽离
![Uniapp common error [wxml file compilation error]./pages/home/home Wxml and using MySQL front provided by phpstudy to establish an independent MySQL database and a detailed tutorial for independent da](/img/21/5dceab9815b503f0b62d26a430d7eb.png)
Uniapp common error [wxml file compilation error]./pages/home/home Wxml and using MySQL front provided by phpstudy to establish an independent MySQL database and a detailed tutorial for independent da

I finished watching this video on my knees at station B
随机推荐
Reproduce the snake game in C language (I) build pages and construct snakes
All codes of Tetris
万字详解“用知识图谱驱动企业业绩增长”
Study notes at the end of summer vacation
Distributed network communication framework: how to publish local services into RPC services
Tower of Hanoi II | tower of Hanoi 4 columns
regular expression
Map key not configured and uniapp routing configuration and jump are reported by the uniapp < map >< /map > component
Study notes of the fifth week of sophomore year
Spolicy request case
Matlab Simulink realizes fuzzy PID control of time-delay temperature control system of central air conditioning
Formwork (III)
Sqoop【环境搭建 01】CentOS Linux release 7.5 安装配置 sqoop-1.4.7 解决警告并验证(附Sqoop1+Sqoop2最新版安装包+MySQL驱动包资源)
在同一conda环境下先装Pytroch后装TensorFlow
Principle analysis and source code interpretation of service discovery
In Net 6.0
Uni app learning summary
Due to fierce competition in the new market, China Mobile was forced to launch a restrictive ultra-low price 5g package
[award-winning question] ask Judea pearl, the Turing prize winner and the father of Bayesian networks
Flutter event distribution