python opencv入门 轮廓的性质(19)

内容来自OpenCV-Python Tutorials 自己翻译整理

长宽比:
边界矩形的宽高比
AspectRation=WidthHeight

import cv2
import numpy as np

img = cv2.imread('3.jpg',0)
#ret,thresh = cv2.threshold(img,127,255,0)
img,contours,hierarchy = cv2.findContours(img, 1, 2)

cnt = contours[1]
x,y,w,h = cv2.boundingRect(cnt)#获取边界
aspect_ratio = float(w)/h#计算比率

print(aspect_ratio)

面积比
轮廓面积与边界矩形的面积比

Extent=ObjectAreaBoundingRectangleArea

import cv2
import numpy as np

img = cv2.imread('3.jpg',0)
#ret,thresh = cv2.threshold(img,127,255,0)
img,contours,hierarchy = cv2.findContours(img, 1, 2)

cnt = contours[1]
area = cv2.contourArea(cnt)#获取轮廓面积
x,y,w,h = cv2.boundingRect(cnt)#获取边界
rect_area = w*h
extent = float(area)/rect_area
print(extent)

凸包面积比
轮廓面积与凸包面积的比

Solidity=ContourAreaConvexHullArea

import cv2
import numpy as np

img = cv2.imread('3.jpg',0)
#ret,thresh = cv2.threshold(img,127,255,0)
img,contours,hierarchy = cv2.findContours(img, 1, 2)

cnt = contours[1]
area = cv2.contourArea(cnt)
hull = cv2.convexHull(cnt)
hull_area = cv2.contourArea(hull)
solidity = float(area)/hull_area
print(solidity)

轮廓直径
与轮廓面积相等的圆形的直径

EquivalentDiameter=4×ContourAreaπ

import cv2
import numpy as np

img = cv2.imread('3.jpg',0)
#ret,thresh = cv2.threshold(img,127,255,0)
img,contours,hierarchy = cv2.findContours(img, 1, 2)

cnt = contours[1]
area = cv2.contourArea(cnt)
equi_diameter = np.sqrt(4*area/np.pi)
print(equi_diameter)

长短轴方向
对象的方向,下面的方法还会返回长轴和短轴的长度

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

蒙板与像素

有时我们需要目标对象在图像里所有像素信息
(这里没使用灰度图)

import cv2
import numpy as np

img = cv2.imread('3.jpg',0)
#ret,thresh = cv2.threshold(img,127,255,0)
img,contours,hierarchy = cv2.findContours(img, 1, 2)

cnt = contours[1]
mask = np.zeros(img.shape,np.uint8)
cv2.drawContours(mask,[cnt],0,255,-1)
pixelpoints = np.transpose(np.nonzero(mask))#像素

此处使用了两种方法,分别为numpy的函数和使用opencv的函数。结果相同,但是numpy给出的是行列值,而opencv给出的是(x,y)形式

最大值和最小值及位置
要用到mask 像素蒙板

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

平均颜色和平均灰度

可以使用相同的蒙板求一个对象的平均颜色或平均灰度

import cv2
import numpy as np

img = cv2.imread('3.jpg',0)
#ret,thresh = cv2.threshold(img,127,255,0)
img,contours,hierarchy = cv2.findContours(img, 1, 2)

cnt = contours[1]
mask = np.zeros(img.shape,np.uint8)
mean_val = cv2.mean(img,mask = mask)
print(mean_val)

极值点
就是求图像中某个对象的最高、最低、最左、最右的点

import cv2
import numpy as np

img = cv2.imread('3.jpg',0)
#ret,thresh = cv2.threshold(img,127,255,0)
img,contours,hierarchy = cv2.findContours(img, 1, 2)

cnt = contours[1]
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])

print(leftmost)

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值