OpenCV學習筆記(14)——輪廓的性質


  • 提取一些經常使用的對象特征

1.長寬比

  邊界矩形的寬高比

                                        

  x,y,w,h = cv2.boundingRect(cnt)

  aspect_ratio = floart(w)/h

2.Extent

  輪廓面積與邊界矩形面積的比。

        

  area = cv2.contourArea(cnt)

  x,y,w,h = cv2.boundingRect(cnt)

  rect_area = w*h

  extent = float(area)/rect_area

3.Solidity

  輪廓面積與凸包面積的比

        

  area = cv2.contourtArea(cnt)

  hull = cv2.convexHull(cnt)

  hull_area = cv2.contourArea(hull)

  solidity = float(area)/hull_area

4.Equivalent Diameter

  與輪廓面積相等的圓形的直徑

        

  area = cv2.contourArea(cnt)

  equi_diameter = np.sqrt(4*area/np.pi)

5.方向

  對象的方向,下面的方法還會返回長軸和短軸的長度

  (x,y),(MA,ma),angle = cv2.fitEllipse(cnt)

6.掩膜和像素點

  有時我們需要構成對象的所有像素點,我們可以這樣做:

  # -*- coding:utf-8 -*-

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

im = cv2.imread('10.png')
img = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)#用這個方式轉換的原因是最后輸出時希望能看到彩色的的輪廓圖
ret,thresh = cv2.threshold(img,127,255,0)

img,contours,hierarchy = cv2.findContours(thresh,1,2)
cnt = contours[0]

mask = np.zeros(im.shape,np.uint8)

cv2.drawContours(mask,[cnt],0,255,-1)#使用-1可以繪制填充的輪廓

#transpose及noozero用法介紹
#Returns a tuple of arrays, one for each dimension of a,
#containing the indices of the non-zero elements in that dimension.
#The result of this is always a 2-D array, with a row for
#each non-zero element.
#To group the indices by element, rather than dimension, use:
#transpose(nonzero(a))
#>>> x = np.eye(3)
#>>> x
#array([[ 1., 0., 0.],
# [ 0., 1., 0.],
# [ 0., 0., 1.]])
#>>> np.nonzero(x)
#(array([0, 1, 2]), array([0, 1, 2]))
#>>> x[np.nonzero(x)]
#array([ 1., 1., 1.])
#>>> np.transpose(np.nonzero(x))
#array([[0, 0],
# [1, 1],
# [2, 2]]
pixelpoints = np.transpose(np.nonzero(mask))

#pixelpoints = cv2.findNonZero(mask)
#兩種方法給出的結果相同,格式不同,前者是(row,column),后者是(x,y),所以這里row = x ,column = y
cv2.imshow('img',mask)
cv2.waitKey(0)

 

7.最大值最小值及它們的位置

  利用上面得到的掩膜圖像可以得到這些參數

  min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(imgray,mask = mask)

  #試了一下,不使用掩膜反而能得到這些參數,使用了就得不到了。

 

8.平均顏色及平均灰度

  可以使用相同的掩膜求一個對象的平均顏色或平均灰度

  mean_val = cv2.mean(im,mask = mask)

 

9,.極點

  一個對象最上面,最下面,最左邊,最右邊的點

  leftmost = tuple(cnt[cnt[:,:,0].argmin()][0])
  rightmost = tuple(cnt[cnt[:,:,0].argmax()][0])
  topmost = tuple(cnt[cnt[:,:,1].argmin()][0])
  bottommost = tuple(cnt[cnt[:,:,1].argmax()][0])


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM