opnencv-python目標檢測-查找目標區域並測量實際尺寸

先感謝大佬(文章引用):https://blog.csdn.net/qq_33854260/article/details/106297999

 

 

這是一個關於預製構件的項目,已經研究好久了   今天把這些貼上來

需要處理的原圖片長這個樣子:

簡單介紹一下,這個東西叫做疊合板,是現在國家大力推廣的裝配式建築裏面的一種常用構件,我們需要識別檢測的就是它的尺寸。即獲得像素塊即可,因爲相機是固定的直接根據實際長度算出來一個比例尺就好了。最主要的是先搞定圖像的處理。

首先對他進行一個灰度圖,二值化的處理,二值化是自動計算閾值的二值化。先看這部分實現的代碼:

import cv2 
import numpy as np
from matplotlib import pyplot as plt

image=cv2.imread('00000008.jpg')   #圖片就在當前目錄下
gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)  #把輸入圖像灰度化
h, w =gray.shape[:2]
m = np.reshape(gray, [1,w*h])
mean = m.sum()/(w*h)

ret, mask_sel =  cv2.threshold(gray, mean, 255, cv2.THRESH_BINARY)


#, contours, hierarchy = cv2.findContours(mask_sel,cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
  
contours,hierarchy = cv2.findContours(mask_sel,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)  

#找到最大區域並填充
#print("contours:",contours)

cv2.namedWindow("mask_sel", cv2.WINDOW_NORMAL)
cv2.imshow("mask_sel", mask_sel)
cv2.waitKey(0)
cv2.destroyAllWindows()    

輸出的是這樣的一個圖片:

接下來需要對二值化的圖形進行一個求最大連通區域的操作。先省略。因爲覺得影響不大。

直接對二值化的圖片進行矩形識別。結果識別不出來,還是連通吧

# -*- coding: utf-8 -*-
"""
Created on Wed May 27 00:31:26 2020

@author: 江湖夜雨十年燈


"""

import cv2 
import numpy as np
from matplotlib import pyplot as plt

image=cv2.imread('00000008.jpg')   #圖片就在當前目錄下
gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)  #把輸入圖像灰度化
h, w =gray.shape[:2]
m = np.reshape(gray, [1,w*h])
mean = m.sum()/(w*h)
ret, mask_sel =  cv2.threshold(gray, mean, 255, cv2.THRESH_BINARY)
#, contours, hierarchy = cv2.findContours(mask_sel,cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
contours,hierarchy = cv2.findContours(mask_sel,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)  
area = []
 
for j in range(len(contours)):   #找到最大區域並填充
 
    area.append(cv2.contourArea(contours[j]))
 
max_idx = np.argmax(area)
 
max_area = cv2.contourArea(contours[max_idx])
 
for k in range(len(contours)):
 
    if k != max_idx:
      cv2.fillPoly(mask_sel, [contours[k]], 0)           #找到最大區域並填充
      
cv2.drawContours(image, contours, -2, (0,255,0), 12)
cv2.drawContours(mask_sel, contours, -2, (0,255,0), 12)
cnt = contours[np.argmax([cv2.contourArea(cnt) for cnt in contours])] 









#找到最大區域並填充
#print("contours:",contours)

cv2.namedWindow("mask_sel", cv2.WINDOW_NORMAL)
cv2.imshow("mask_sel", mask_sel)

#cv2.imshow("mask_se2l", hierarchy)
cv2.waitKey(0)
cv2.destroyAllWindows()    





是這樣一個效果,疊合板這種東西和那些流水線的零件還不一樣,現場條件太差。

下次接着寫

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章