当前位置:网站首页>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 .

边栏推荐
- Study notes of the second week of sophomore year
- Getting started with SQL - combined tables
- Set view dynamic picture
- SQL优化的魅力!从 30248s 到 0.001s
- The use of MySQL in nodejs
- Beginner of flask framework-04-flask blueprint and code separation
- Force deduction DFS
- Wechat applet learning notes 2
- Opencv image processing
- 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
猜你喜欢

Vs Code configures go locale and successfully installs go related plug-ins in vscode problem: Tools failed to install

Meeting OA project (III) -- my meeting (meeting seating and submission for approval)

分布式网络通信框架:本地服务怎么发布成RPC服务

Flask框架初学-03-模板

Sqoop【环境搭建 01】CentOS Linux release 7.5 安装配置 sqoop-1.4.7 解决警告并验证(附Sqoop1+Sqoop2最新版安装包+MySQL驱动包资源)

regular expression

Leetcode 504. Hex number

万字详解“用知识图谱驱动企业业绩增长”

解决ProxyError: Conda cannot proceed due to an error in your proxy configuration.

30分钟彻底弄懂 synchronized 锁升级过程
随机推荐
如何写一篇百万阅读量的文章
Wechat applet learning notes 2
SQL优化的魅力!从 30248s 到 0.001s
Study notes of the fifth week of sophomore year
Error in render: "typeerror: cannot read properties of undefined (reading 'length')" --- error when calling interface
苹果独占鳌头,三星大举复兴,国产手机在高端市场颗粒无收
IE7 set overflow attribute failure solution
输入整数后输入整行字符串的解决方法
SQL Server 2008 R2 installation problems
Rowselection emptying in a-table
Introduction to latex, EPS picture bounding box
AirTest
IEEE conference upload font problem
PHP executes shell script
服务器内存故障预测居然可以这样做!
数通基础-Telnet远程管理设备
Solve the problem of storing cookies in IE7 & IE8
点赞,《新程序员》电子书限时免费领啦!
The diagram of user login verification process is well written!
Formwork (III)