OpenCV图像轮廓的简单学习

学了一点基本函数的用法,后面的感觉不怎么理解,就没敲了

import numpy as np
import cv2 as cv
im = cv.imread('E:\\python opencv\\demo2\\aa1.png')
cv.imshow('im', im)
#转换为灰度图像
imgray = cv.cvtColor(im, cv.COLOR_BGR2GRAY)
cv.imshow('imgray', imgray)
#设置阈值
ret, thresh = cv.threshold(imgray, 240, 255, 0)
cv.imshow('thresh', thresh)
#找轮廓,第一个为源图像,第二个为轮廓检索模式,第三个为轮廓逼近方法
contours, hierarchy = cv.findContours(thresh, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)
#cv.imshow('hierarchy',contours)
cnt = contours[0]
#提供了所有计算出的矩值的字典
M = cv.moments(cnt)
print(M)
#求轮廓的面积
area = cv.contourArea(cnt)
print(area)
#求轮廓周长
perimeter = cv.arcLength(cnt, True)
print(perimeter)
#轮廓近似
epsilon = 0.1*cv.arcLength(cnt, True)
approx = cv.approxPolyDP(cnt, epsilon, True)
#检查凸度
k = cv.isContourConvex(cnt)
print(k)
#获取边界矩形
x, y, w, h = cv.boundingRect(cnt)
cv.rectangle(im, (x, y), (x+w, y+h), (0, 0, 255), 2)
cv.imshow('im1', im)
#旋转矩形绘制,最小面积
rect = cv.minAreaRect(cnt)
box = cv.boxPoints(rect)
box = np.int0(box)
cv.drawContours(im, [box], 0, (255, 0, 0), 2)
cv.imshow('im2', im)
#拟合一个圆
(x, y), radius = cv.minEnclosingCircle(cnt)
center = (int(x), int(y))
radius = int(radius)
cv.circle(im, center, radius, (0, 255, 0), 2)
cv.imshow('im3', im)
#拟合一个椭圆
ellipse = cv.fitEllipse(cnt)
cv.ellipse(im, ellipse, (0, 255, 0), 2)
cv.imshow('im4', im)
#拟合直线
rows, cols = im.shape[:2]
[vx, vy, x, y] = cv.fitLine(cnt, cv.DIST_L2, 0, 0.01, 0.01)
lefty = int((-x*vy/vx)+y)
righty = int(((cols-x)*vy/vx)+y)
cv.line(im, (cols-1, righty), (0, lefty), (0, 255, 0), 2)
cv.imshow('im5', im)

cv.waitKey(0)
cv.destroyAllWindows()

唉,搞什么东西都不容易,渣渣

你可能感兴趣的:(OpenCV学习之路)