本小节将要学习提取一些经常使用的对象特征,可以在Matlab regionprops documentation 更多的图像特征。
import cv2
import numpy as np
# img = cv2.imread('messimg.png',0)
img = cv2.imread('./star.jpg', 0)
ret,thresh = cv2.threshold(img,127,255,0)
contours,hierarchy= cv2.findContours(thresh, 1, 2)
cnt = contours[0]
x,y,w,h = cv2.boundingRect(cnt)
aspect_ratio = float(w)/h
area = cv2.contourArea(cnt)
x,y,w,h = cv2.boundingRect(cnt)
rect_area = w*h
extent = float(area)/rect_area
area = cv2.contourArea(cnt)
hull = cv2.convexHull(cnt)
hull_area = cv2.contourArea(hull)
solidity = float(area)/hull_area
area = cv2.contourArea(cnt)
equi_diameter = np.sqrt(4*area/np.pi)
(x,y),(MA,ma),angle = cv2.fitEllipse(cnt)
mask = np.zeros(imgray.shape,np.uint8)
#这里一定要使用参数 -1, 绘制填充的的轮廓
cv2.drawContours(mask,[cnt],0,255,-1)
#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)
#官方代码
mask = np.zeros(imgray.shape,np.uint8)
cv2.drawContours(mask,[cnt],0,255,-1)
pixelpoints = np.transpose(np.nonzero(mask))
#pixelpoints = cv2.findNonZero(mask)
--------------------------------------------------------------------------- NameError Traceback (most recent call last) Cell In[7], line 1 ----> 1 mask = np.zeros(imgray.shape,np.uint8) 2 #这里一定要使用参数 -1, 绘制填充的的轮廓 3 cv2.drawContours(mask,[cnt],0,255,-1) NameError: name 'imgray' is not defined
这里采用两种方法,第一种方法使用了 Numpy 函数,第二种使用了 OpenCV 函数。 结果相同,但还是有点不同。Numpy 给出的坐标是 (row ,colum )形式的。 而 OpenCV 给出的格式是 (x ,y )形式的。所以这两个结果基本是可以互换的。row=x,colunm=y。
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(imgray,mask = mask)
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(imgray,mask = mask)
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])
如下图所示:
练习
- Matlab regionprops 文档中还有一些图像特征在这里没有讲到,可以尝试着使用 Python 和 OpenCV 来实现他们。