图像轮廓

图像轮廓_其它

import cv2 as cv
import numpy as np
import matplotlib.pyplot as plt

def display_img(img):
cv.imshow('image',img)
cv.waitKey(0)
cv.destroyAllWindows()


def operate_img(file):
img = cv.imread(file)#imread(file,cv.IMREAD_GRAYSCALE)
gray = cv.cvtColor(img,cv.COLOR_BGR2GRAY)
ret,thresh = cv.threshold(gray,127,255,cv.THRESH_BINARY)
#display_img(thresh)
contours,hierachy = cv.findContours(thresh,cv.RETR_TREE,cv.CHAIN_APPROX_NONE)
con_img = img.copy()
res = cv.drawContours(con_img,contours,-1,(0,255,5),2)
display_img(res)
cors= contours[0]
area = cv.contourArea(cors)
line_len = cv.arcLength(cors,True)
print (area,line_len )


operate_img(file="gui.jpeg")

图像轮廓_其它_02

轮廓近似

def operate_img(file):
img = cv.imread(file)#imread(file,cv.IMREAD_GRAYSCALE)
gray = cv.cvtColor(img,cv.COLOR_BGR2GRAY)
ret,thresh = cv.threshold(gray,127,255,cv.THRESH_BINARY)
#display_img(thresh)
contours,hierachy = cv.findContours(thresh,cv.RETR_TREE,cv.CHAIN_APPROX_NONE)

cors= contours[-1]
area = cv.contourArea(cors)
line_len = cv.arcLength(cors,True)
print (area,line_len )

epsilon = 0.01*line_len
approx = cv.approxPolyDP(cors,epsilon,True)
con_img = img.copy()
res = cv.drawContours(con_img,[approx],-1,(0,255,5),2)
display_img(res)

图像轮廓_其它_03

矩形近似

def jvxing_img(file):
img = cv.imread(file)#imread(file,cv.IMREAD_GRAYSCALE)
gray = cv.cvtColor(img,cv.COLOR_BGR2GRAY)
ret,thresh = cv.threshold(gray,127,255,cv.THRESH_BINARY)
#display_img(thresh)
contours,hierachy = cv.findContours(thresh,cv.RETR_TREE,cv.CHAIN_APPROX_NONE)
cors= contours[-1]
area = cv.contourArea(cors)
x,y,w,h = cv.boundingRect(cors)
rect_area = w*h
extent = float(area)/rect_area
print ("轮廓面积与边界面积比例",extent)

x,y,w,h = cv.boundingRect(cors)
img = cv.rectangle(img,(x,y),(x+w,y+h),(0,255,9),2)
display_img(img)

图像轮廓_其它_04

圆形近似

def circle_img(file):
img = cv.imread(file)#imread(file,cv.IMREAD_GRAYSCALE)
gray = cv.cvtColor(img,cv.COLOR_BGR2GRAY)
ret,thresh = cv.threshold(gray,127,255,cv.THRESH_BINARY)
#display_img(thresh)
contours,hierachy = cv.findContours(thresh,cv.RETR_TREE,cv.CHAIN_APPROX_NONE)
cors= contours[-1]
(x,y),r= cv.minEnclosingCircle(cors)
center = (int(x),int(y))
r = int(r)
img = cv.circle(img,center,r,(0,255,9),2)
display_img(img)

图像轮廓_其它_05