# coding: utf-8
# !/usr/bin/python
"""
@File : 轮廓的性质.py
@Author : jiaming
@Modify Time: 2020/2/5 15:25
@Contact :
@Version : 1.0
@Desciption : None
"""
import os
import sys
import numpy as np
import cv2
import pprint
from matplotlib import pyplot as plt
rawPath = os.path.abspath(__file__)
currentFile = os.path.basename(sys.argv[0])
dataPath = rawPath[:rawPath.find(currentFile)] + r'static\\'
边界矩形的宽高比
"""
边界矩形的宽高比
"""
img = cv2.imread(dataPath + 'j.png', 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_ration = float(w) / h # 1.375
print('aspect_ration', aspect_ration)
轮廓面积与边界矩形面积的比
"""
轮廓面积与边界矩形面积的比
"""
img = cv2.imread(dataPath + 'j.png', 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)
area = cv2.contourArea(cnt)
x, y, w, h = cv2.boundingRect(cnt)
rect_area = w*h
extent = float(area) / rect_area
print('extent', extent) # 0.5353535353535354
轮廓面积与凸包面积的比
"""
轮廓面积与凸包面积的比
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)
cv2.drawContours(mask, [cnt], 0, 255, -1)
pixelpoints = np.transpose(np.nonzero(mask)) 或
pixelpoints = cv2.findNonZero(mask)
"""
最大值及它们的位置
"""
最大值及它们的位置
通过使用掩模图像得到这些参数
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(imgray, mask=mask)
"""
平均颜色及平均灰度
"""
平均颜色及平均灰度
我们也可以使用相同的掩模求一个对象的平均颜色或平均灰度
mean_val = cv2.mean(im, 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])
"""