基于python的opencv项目实战笔记(六)—— 图像金字塔与轮廓检测

import cv2 as cv
import matplotlib.pyplot as plt
import numpy as np
def cv_show(name,img):
    cv.imshow(name,img)
    cv.waitKey(0)
    cv.destroyAllWindows()
#高斯金字塔
#上采样
def cv_pyrUp(img):
    up=cv.pyrUp(img)
    cv_show('up',up)
    print(up.shape)
#下采样
def cv_pyrDown(img):
    down=cv.pyrDown(img)
    cv_show('down',down)
    print(down.shape)
#上下采样,会损失信息
def cv_ud(img):
    up = cv.pyrUp(img)
    down = cv.pyrDown(up)
    res=np.hstack((img,down))
    cv_show('res', res)
    print(down.shape)
#拉普拉斯金字塔
def cv_la(img):
    down =cv.pyrDown(img)
    down_up =cv.pyrUp(down)
    down_up=cv.resize(down_up,(621,667))
    print(down_up.shape)
    la=img-down_up
    cv_show('la',la)
#图像轮廓(是一个整体)
def cv_contour1():
    #检索轮廓
    img=cv.imread("D://c2.png")
    gray=cv.cvtColor(img,cv.COLOR_BGR2GRAY)#转化为灰度图,更好进行边缘检测
    ret,thresh=cv.threshold(gray,127,255,cv.THRESH_BINARY)#大于127的为255,小于为0
    #cv_show('thresh',thresh)
    #第一个值为轮廓信息,第二个值为层级
    contours,hierarchy=cv.findContours(thresh,cv.RETR_TREE,cv.CHAIN_APPROX_NONE)#第二个参数检索所有轮廓,第三个画出所有点
    #绘制轮廓
    draw_img=img.copy()
    res=cv.drawContours(draw_img,contours,-1,(0,0,255),2)#-1标出所有,其他数字为顺序选择
    #cv_show('res',res)
    #轮廓特征
    cnt=contours[0]#第0个轮廓
    area=cv.contourArea(cnt)#计算面积
    length=cv.arcLength(cnt,True)#周长,True表示闭合
    print(area)
    print(length)
#轮廓近似
def cv_contour2():
    img1 = cv.imread("D://c3.png")
    gray = cv.cvtColor(img1, cv.COLOR_BGR2GRAY)
    ret, thresh = cv.threshold(gray, 127, 255, cv.THRESH_BINARY)
    contours, hierarchy = cv.findContours(thresh, cv.RETR_TREE, cv.CHAIN_APPROX_NONE)
    cnt=contours[0]
    draw_img = img1.copy()
    res = cv.drawContours(draw_img,[cnt], -1, (0, 0, 255), 2)
    epsilon=0.1*cv.arcLength(cnt,True)#值越小近似越小,越大近似越大
    approx=cv.approxPolyDP(cnt,epsilon,True)
    draw_img = img1.copy()
    res = cv.drawContours(draw_img,[approx], -1, (0, 0, 255), 2)
    cv_show('res', res)
#边界矩形
def cv_contour3():
    src = cv.imread("D://c2.png")
    gray = cv.cvtColor(src, cv.COLOR_BGR2GRAY)
    ret, thresh = cv.threshold(gray, 127, 255, cv.THRESH_BINARY)
    contours, hierarchy = cv.findContours(thresh, cv.RETR_TREE, cv.CHAIN_APPROX_NONE)
    cnt = contours[0]
    area=cv.contourArea(cnt)
    x,y,w,h=cv.boundingRect(cnt)
    rect_area=w*h
    extent=float(area)/rect_area
    print('轮廓面积与边界矩形比:',extent)
    src=cv.rectangle(src,(x,y),(x+w,y+h),(0,255,0),2)
    cv_show('src',src)
#外接圆
def cv_contour4():
    src = cv.imread("D://c2.png")
    gray = cv.cvtColor(src, cv.COLOR_BGR2GRAY)
    ret, thresh = cv.threshold(gray, 127, 255, cv.THRESH_BINARY)
    contours, hierarchy = cv.findContours(thresh, cv.RETR_TREE, cv.CHAIN_APPROX_NONE)
    cnt = contours[0]
    (x, y),r= cv.minEnclosingCircle(cnt)
    center=(int(x),int(y))
    r=int(r)
    src=cv.circle(src,center,r,(0,255,0),2)
    cv_show('src', src)
#模板匹配
#从左到右,从上到下,进行匹配
def cv_tm():
    img=cv.imread('D://l2.png',0)
    template=cv.imread('D://l.png',0)
    h,w=template.shape[:2]
    methods = ['cv.TM_CCOEFF', 'cv.TM_CCOEFF_NORMED', 'cv.TM_CCORR',
               'cv.TM_CCORR_NORMED', 'cv.TM_SQDIFF', 'cv.TM_SQDIFF_NORMED']
    res = cv.matchTemplate(img, template, cv.TM_SQDIFF)
    min_val, max_val, min_loc, max_loc = cv.minMaxLoc(res)
    for meth in methods:
        img2 = img.copy()
        method = eval(meth)
        print(method)  # 匹配方法的真值
        res = cv.matchTemplate(img, template, method)
        min_val, max_val, min_loc, max_loc = cv.minMaxLoc(res)
    '''
     如果是平方差匹配TM_SQDIFF或归一化平方差匹配TM_SQDIFF_NORMED,取最小值
    '''
    if method in [cv.TM_SQDIFF, cv.TM_SQDIFF_NORMED]:
        top_left = min_loc
    else:
        top_left = max_loc
    bottom_right = (top_left[0] + w, top_left[1] + h)
    cv.rectangle(img2, top_left, bottom_right, 255, 2)  # 画矩形
    plt.subplot(121), plt.imshow(res, cmap='gray')
    plt.xticks([]), plt.yticks([])  # 隐藏坐标轴
    plt.subplot(122), plt.imshow(img2, cmap='gray')
    plt.xticks([]), plt.yticks([])
    plt.suptitle(meth)
    plt.show()
#匹配多个对象
def cv_tm1():
    img_rgb = cv.imread('D://m.png')
    img_gray = cv.cvtColor(img_rgb, cv.COLOR_BGR2GRAY)
    template = cv.imread('D://m1.png', 0)
    h,w = template.shape[:2]
    res = cv.matchTemplate(img_gray, template, cv.TM_CCOEFF_NORMED)
    threshold = 0.8  # 取匹配程度大于%80的坐标
    loc = np.where(res >= threshold)
    for pt in zip(*loc[::-1]):  # *号表示可选参数
        bottom_right = (pt[0] + w, pt[1] + h)
        cv.rectangle(img_rgb, pt, bottom_right, (0, 0, 255), 2)
    cv.imshow('img_rgb', img_rgb)
    cv.waitKey(0)
img=cv.imread('D://z2.png')
#cv_show('img',img)
#print(img.shape)
#cv_pyrUp(img)
#cv_pyrDown(img)
#cv_ud(img)
#cv_la(img)
#cv_contour1()
#cv_contour2()
#cv_contour3()
#cv_contour4()
#cv_tm()
cv_tm1()

上一篇:对于七段数码数字模型进行改进:一个关键的数字1的问题


下一篇:RGB图像转换为灰度图像的原理