• 计算机视觉快速入门一 —— 图像基本操作(二)


    计算机视觉快速入门一 —— 图像基本操作(二)

    1.灰度图

    img_gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)

    import cv2 #opencv读取的格式是BGR
    import numpy as np
    import matplotlib.pyplot as plt#Matplotlib是RGB
    %matplotlib inline 
    
    img=cv2.imread('cat.jpg')
    img_gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
    img_gray.shape #二维(414,500)
    cv2.imshow("img_gray", img_gray)
    cv2.waitKey(0)    
    cv2.destroyAllWindows() 
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    2.HSV

    H-色调(主波长)
    S-饱和度(纯度/颜色的阴影)
    V值(强度)
    hsv=cv2.cvtColor(img,cv2.COLOR_BGR2HSV)

    hsv=cv2.cvtColor(img,cv2.COLOR_BGR2HSV)
    
    cv2.imshow("hsv", hsv)
    cv2.waitKey(0)    
    cv2.destroyAllWindows()
    
    • 1
    • 2
    • 3
    • 4
    • 5

    3.图像阈值

    • ret,dst=cv2.threshold(src,thresh,maxval,type)

    • dst:输出图

    • src:输入图,只能输入单通道,通常来说是灰度图

    • thresh:阈值

    • maxval: 当像素值超过了阈值(或者小于阈值,根据type来决定),所赋予的值

    • type:二值化操作的类型,包含以下5种类型: cv2.THRESH_BINARY; cv2.THRESH_BINARY_INV; cv2.THRESH_TRUNC; cv2.THRESH_TOZERO;cv2.THRESH_TOZERO_INV

    • cv2.THRESH_BINARY 超过阈值部分maxval(最大值),否则取0

    • cv2.THRESH_BINARY_INV THRESH_BINARY的反转

    • cv2.THRESH_TRUNC 大于阈值部分设为阈值,否则不变

    • cv2.THRESH_TOZERO 大于阈值部分不改变,否则设为0

    • cv2.THRESH_TOZERO_INV THRESH_TOZERO的反转

    ret, thresh1 = cv2.threshold(img_gray, 127, 255, cv2.THRESH_BINARY)
    ret, thresh2 = cv2.threshold(img_gray, 127, 255, cv2.THRESH_BINARY_INV)
    ret, thresh3 = cv2.threshold(img_gray, 127, 255, cv2.THRESH_TRUNC)
    ret, thresh4 = cv2.threshold(img_gray, 127, 255, cv2.THRESH_TOZERO)
    ret, thresh5 = cv2.threshold(img_gray, 127, 255, cv2.THRESH_TOZERO_INV)
    
    titles = ['Original Image', 'BINARY', 'BINARY_INV', 'TRUNC', 'TOZERO', 'TOZERO_INV']
    images = [img, thresh1, thresh2, thresh3, thresh4, thresh5]
    
    for i in range(6):
        plt.subplot(2, 3, i + 1), plt.imshow(images[i], 'gray')
        plt.title(titles[i])
        plt.xticks([]), plt.yticks([])
    plt.show()
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    在这里插入图片描述

    4.图像平滑

    • 均值滤波,简单的平均卷积操作 blur=cv2.blur(img,(3,3))
    • 方框滤波,基本和均值一样,可以选择归一化,容易越界 box = cv2.boxFilter(img,-1,(3,3),normalize=False)
    • 高斯滤波,高斯模糊的卷积核里的数值是满足高斯分布,相当于更重视中间的aussian=cv2.GaussianBlur(img, (5, 5), 1)
    • 中值滤波,相当于用中值代替 median = cv2.medianBlur(img, 5)

    5.形态学

    需要设置卷积内核kernel = np.ones((3,3),np.uint8)

    • 腐蚀操作 erosion = cv2.erode(img,kernel,iterations = 1)
    • 膨胀操作dige_dilate=cv2.dilate(dige_erosion,kernel,iterations = 1)
    • 开运算(先腐蚀,再膨胀)opening = cv2.morphologyEx(img, cv2.MORPH_OPEN, kernel)
    • 闭运算(先膨胀,再腐蚀)closing = cv2.morphologyEx(img, cv2.MORPH_CLOSE, kernel)
    • 梯度运算(梯度=膨胀-腐蚀)gradient = cv2.morphologyEx(pie, cv2.MORPH_GRADIENT, kernel)
    • 礼帽(礼帽=原始输入-开运算结果) tophat = cv2.morphologyEx(img, cv2.MORPH_TOPHAT, kernel)
    • 黑帽(黑帽=闭运算-原始输入)blackhat = cv2.morphologyEx(img,cv2.MORPH_BLACKHAT, kernel)

    6.图像梯度

    (1)图像梯度-Sobel算子
    dst = cv2.Sobel(src, ddepth, dx, dy, ksize)

    • ddepth:图像的深度
    • dx和dy分别表示水平和竖直方向
    • ksize是Sobel算子的大小
      在这里插入图片描述
    img = cv2.imread('pie.png',cv2.IMREAD_GRAYSCALE)
    def cv_show(img,name):
        cv2.imshow(name,img)
        cv2.waitKey()
        cv2.destroyAllWindows()
    sobelx = cv2.Sobel(img,cv2.CV_64F,1,0,ksize=3)
    cv_show(sobelx,'sobelx')
    #白到黑是正数,黑到白就是负数了,所有的负数会被截断成0,所以要取绝对值
    sobelx = cv2.convertScaleAbs(sobelx)
    cv_show(sobelx,'sobelx')
    sobely = cv2.Sobel(img,cv2.CV_64F,0,1,ksize=3)
    sobely = cv2.convertScaleAbs(sobely)  
    cv_show(sobely,'sobely')
    
    #分别计算x和y,再求和
    sobelxy = cv2.addWeighted(sobelx,0.5,sobely,0.5,0)
    cv_show(sobelxy,'sobelxy')
    #不建议直接计算
    sobelxy=cv2.Sobel(img,cv2.CV_64F,1,1,ksize=3)
    sobelxy = cv2.convertScaleAbs(sobelxy) 
    cv_show(sobelxy,'sobelxy')
    
    img = cv2.imread('lena.jpg',cv2.IMREAD_GRAYSCALE)
    cv_show(img,'img')
    img = cv2.imread('lena.jpg',cv2.IMREAD_GRAYSCALE)
    sobelx = cv2.Sobel(img,cv2.CV_64F,1,0,ksize=3)
    sobelx = cv2.convertScaleAbs(sobelx)
    sobely = cv2.Sobel(img,cv2.CV_64F,0,1,ksize=3)
    sobely = cv2.convertScaleAbs(sobely)
    sobelxy = cv2.addWeighted(sobelx,0.5,sobely,0.5,0)
    res = np.hstack((sobelx,sobely,sobelxy))
    cv_show(res,'sobel')
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32

    在这里插入图片描述
    (2)图像梯度-Scharr算子
    在这里插入图片描述
    (3)图像梯度-laplacian算子
    在这里插入图片描述

    #不同算子的差异
    img = cv2.imread('lena.jpg',cv2.IMREAD_GRAYSCALE)
    sobelx = cv2.Sobel(img,cv2.CV_64F,1,0,ksize=3)
    sobely = cv2.Sobel(img,cv2.CV_64F,0,1,ksize=3)
    sobelx = cv2.convertScaleAbs(sobelx)   
    sobely = cv2.convertScaleAbs(sobely)  
    sobelxy =  cv2.addWeighted(sobelx,0.5,sobely,0.5,0)  
    
    scharrx = cv2.Scharr(img,cv2.CV_64F,1,0)
    scharry = cv2.Scharr(img,cv2.CV_64F,0,1)
    scharrx = cv2.convertScaleAbs(scharrx)   
    scharry = cv2.convertScaleAbs(scharry)  
    scharrxy =  cv2.addWeighted(scharrx,0.5,scharry,0.5,0) 
    
    laplacian = cv2.Laplacian(img,cv2.CV_64F)
    laplacian = cv2.convertScaleAbs(laplacian)   
    
    res = np.hstack((sobelxy,scharrxy,laplacian))
    cv_show(res,'res')
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

    在这里插入图片描述

    7.Canny边缘检测

    • 1 使用高斯滤波器,以平滑图像,滤除噪声。
      在这里插入图片描述

    • 2 计算图像中每个像素点的梯度强度和方向。
      在这里插入图片描述

    • 3 应用非极大值(Non-Maximum Suppression)抑制,以消除边缘检测带来的杂散响应。
      在这里插入图片描述

    • 4 应用双阈值(Double-Threshold)检测来确定真实的和潜在的边缘。
      在这里插入图片描述

    • 5 通过抑制孤立的弱边缘最终完成边缘检测。

    img=cv2.imread("lena.jpg",cv2.IMREAD_GRAYSCALE)
    
    v1=cv2.Canny(img,80,150)
    v2=cv2.Canny(img,50,100)
    
    res = np.hstack((v1,v2))
    cv_show(res,'res')
    img=cv2.imread("car.png",cv2.IMREAD_GRAYSCALE)
    
    v1=cv2.Canny(img,120,250)
    v2=cv2.Canny(img,50,100)
    
    res = np.hstack((v1,v2))
    cv_show(res,'res')
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    在这里插入图片描述

    8.图像金字塔

    • 高斯金字塔:向下采样方法(缩小)、向上采样方法(放大)
      在这里插入图片描述
    down=cv2.pyrDown(img)
    up=cv2.pyrUp(img)
    
    • 1
    • 2
    • 拉普拉斯金字塔
      在这里插入图片描述
    down=cv2.pyrDown(img)
    down_up=cv2.pyrUp(down)
    l_1=img-down_up
    cv_show(l_1,'l_1')
    
    • 1
    • 2
    • 3
    • 4

    9.图像轮廓

    cv2.findContours(img,mode,method)
    (1) mode:轮廓检索模式

    • RETR_EXTERNAL :只检索最外面的轮廓;
    • RETR_LIST:检索所有的轮廓,并将其保存到一条链表当中;
    • RETR_CCOMP:检索所有的轮廓,并将他们组织为两层:顶层是各部分的外部边界,第二层是空洞的边界;
    • RETR_TREE:检索所有的轮廓,并重构嵌套轮廓的整个层次;

    (2) method:轮廓逼近方法

    • CHAIN_APPROX_NONE:以Freeman链码的方式输出轮廓,所有其他方法输出多边形(顶点的序列)。
    • CHAIN_APPROX_SIMPLE:压缩水平的、垂直的和斜的部分,也就是,函数只保留他们的终点部分。
    # 为了更高的准确率,使用二值图像
    """
    第一步:载入图片
    第二步:使用cv2.cvtcolor() 将图片转换为灰度图
    第三步: 使用cv2.threshold将图片做二值化转换
    第四步:使用cv2.findContours 找出图片的轮廓值
    第五步:使用cv2.drawContours在图片上画上轮廓
    第六步: 使用cv2.imshow 完成画图操作
    """
    def cv_show(img, name):
        cv2.imshow(name, img)
        cv2.waitKey(0)
        cv2.destroyAllWindows()
     
     
    # 第一步读入图片
    img = cv2.imread('contours.png')
    # 第二步:对图片做灰度变化
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    # 第三步:对图片做二值变化
    ret, thresh = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)
    # 第四步:获得图片的轮廓值
    contours, h = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
     
    # 第五步:在图片中画出图片的轮廓值
    # 参数说明,draw_img 需要作图的原始图像, contours表示轮廓, 0表示轮廓索引, (0, 0, 255)表示颜色, 2表示线条粗细
    draw_img = img.copy()
    ret = cv2.drawContours(draw_img, contours, -1, (0, 0, 255), 2)
    # 第六步:画出带有轮廓的原始图片
    cv_show(ret,'ret')
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30

    (3)轮廓特征

    # 取出单个的轮廓值
    cnt = contours[0]
     
    # 第二步:计算轮廓的面积
    area = cv2.contourArea(cnt)
     
    # 第三步: 计算轮廓的周长
    length= cv2.arcLength(cnt, True)
    print(area, length)
     
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    (4)轮廓近似(RDP):假设存在一个曲线A, B,在曲线上存在一个C点,离AB线段的距离最远,记为d1, 如果d1 < T(自己设定的阈值), 将AB线段作为AB曲线的替代,否者连接AC和BC, 计算AC线段上的D点离AB距离最远,记为d2,如果d2 < T,则使用AC线段替代AC曲线,否者继续连接划

    # 轮廓近似
    img = cv2.imread('contours2.png')
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    ret, thresh = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)
     
    contours, h = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
     
    cnt = contours[0]
     
    # 使用周长的倍数作为阈值,阈值越小,图像的轮廓近似与轮廓越近似
    epsilon = 0.1 * cv2.arcLength(cnt, True)
     
    approx = cv2.approxPolyDP(cnt, epsilon, True)
     
    draw_img = img.copy()
    ret = cv2.drawContours(draw_img, [approx], -1, (0, 0, 255), 2)
    cv_show(ret, 'ret')
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    (5)外接矩形和外接圆

    外接矩形: 使用cv2.boudingrect(cnt)获得轮廓的外接矩形,使用cv2.rectangle(img, (x, y), (x+w, y+h), (0, 0, 255), 2)画出矩阵的轮廓

    外接圆: 使用cv2.minEnclosingCircle(cnt)获得轮廓的外接圆,使用cv2.circle(ret, centers, radius, (0, 0, 255), 2)画出圆的轮廓

    
    """
    第一步:载入图片,灰度化,二值化,使用cv2.findCountors找出图像的轮廓,使用轮廓索引获得第一个轮廓cnt
    第二步:使用cv2.boundingrect(cnt) ,获得轮廓的x,y,w, h (x, y)表示左上角的坐标,w为宽,h为长
    第三步: 使用cv2.rectangle 绘制外接的轮廓
    第四步: 使用cv2.minEnclosingCircle(cnt), 获得center和radius,即圆心点的坐标和圆的半径
    第五步: 使用cv2.circle(img, center, radius, (0, 0, 255), 2) 绘制圆心的外接轮廓
    """
     
    # 外接矩阵
     
    img = cv2.imread('contours.png')
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    res, thresh = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)
     
    binary, contours, h = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
     
    cnt = contours[0]
     
    x, y, w, h = cv2.boundingRect(cnt)
     
    ret = cv2.rectangle(img, (x, y), (x+w, y+h), (0, 0, 255), 2)
    cv_show(ret, 'ret')
     
    print('矩形面积 / 外接矩形面积', cv2.contourArea(cnt) / (w*h))
    
    # 外接圆
    (x, y), radius = cv2.minEnclosingCircle(cnt)
    center = (int(x), int(y))
    radius = int(radius)
    ret = cv2.circle(ret, center, radius, (0, 255, 0), 2)
    cv_show(ret, 'ret')
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33

    10.傅里叶变换

    (1)傅里叶变换的作用-将图像转化为频谱

    • 高频:变化剧烈的灰度分量,例如边界

    • 低频:变化缓慢的灰度分量,例如一片大海

    (2) 滤波

    • 低通滤波器:只保留低频,会使得图像模糊

    • 高通滤波器:只保留高频,会使得图像细节增强

    • opencv中主要就是cv2.dft()和cv2.idft(),输入图像需要先转换成np.float32 格式。

    • 得到的结果中频率为0的部分会在左上角,通常要转换到中心位置,可以通过shift变换来实现。

    • cv2.dft()返回的结果是双通道的(实部,虚部),通常还需要转换成图像格式才能展示(0,255)。

    import numpy as np
    import cv2
    from matplotlib import pyplot as plt
    
    img = cv2.imread('lena.jpg',0)
    
    img_float32 = np.float32(img)
    
    dft = cv2.dft(img_float32, flags = cv2.DFT_COMPLEX_OUTPUT)
    dft_shift = np.fft.fftshift(dft)
    # 得到灰度图能表示的形式
    magnitude_spectrum = 20*np.log(cv2.magnitude(dft_shift[:,:,0],dft_shift[:,:,1]))
    
    plt.subplot(121),plt.imshow(img, cmap = 'gray')
    plt.title('Input Image'), plt.xticks([]), plt.yticks([])
    plt.subplot(122),plt.imshow(magnitude_spectrum, cmap = 'gray')
    plt.title('Magnitude Spectrum'), plt.xticks([]), plt.yticks([])
    plt.show()
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    import numpy as np
    import cv2
    from matplotlib import pyplot as plt
    
    img = cv2.imread('lena.jpg',0)
    
    img_float32 = np.float32(img)
    
    dft = cv2.dft(img_float32, flags = cv2.DFT_COMPLEX_OUTPUT)
    dft_shift = np.fft.fftshift(dft)
    
    rows, cols = img.shape
    crow, ccol = int(rows/2) , int(cols/2)     # 中心位置
    
    # 低通滤波
    mask = np.zeros((rows, cols, 2), np.uint8)
    mask[crow-30:crow+30, ccol-30:ccol+30] = 1
    
    # IDFT
    fshift = dft_shift*mask
    f_ishift = np.fft.ifftshift(fshift)
    img_back = cv2.idft(f_ishift)
    img_back = cv2.magnitude(img_back[:,:,0],img_back[:,:,1])
    
    plt.subplot(121),plt.imshow(img, cmap = 'gray')
    plt.title('Input Image'), plt.xticks([]), plt.yticks([])
    plt.subplot(122),plt.imshow(img_back, cmap = 'gray')
    plt.title('Result'), plt.xticks([]), plt.yticks([])
    
    plt.show()  
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    img = cv2.imread('lena.jpg',0)
    
    img_float32 = np.float32(img)
    
    dft = cv2.dft(img_float32, flags = cv2.DFT_COMPLEX_OUTPUT)
    dft_shift = np.fft.fftshift(dft)
    
    rows, cols = img.shape
    crow, ccol = int(rows/2) , int(cols/2)     # 中心位置
    
    # 高通滤波
    mask = np.ones((rows, cols, 2), np.uint8)
    mask[crow-30:crow+30, ccol-30:ccol+30] = 0
    
    # IDFT
    fshift = dft_shift*mask
    f_ishift = np.fft.ifftshift(fshift)
    img_back = cv2.idft(f_ishift)
    img_back = cv2.magnitude(img_back[:,:,0],img_back[:,:,1])
    
    plt.subplot(121),plt.imshow(img, cmap = 'gray')
    plt.title('Input Image'), plt.xticks([]), plt.yticks([])
    plt.subplot(122),plt.imshow(img_back, cmap = 'gray')
    plt.title('Result'), plt.xticks([]), plt.yticks([])
    
    plt.show()  
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
  • 相关阅读:
    android嵌入式开发及实训答案,android面试简历模板
    6.filters滤波
    判断2叉树是否为对称树(C#)
    批量条件赋值、文本字段计算常用表达式
    自定义Docker镜像--Jupyterlab
    快手小程序模板_快手小程序模板平台制作
    EasyExcel的简单读取操作
    Centos7,yum安装mysql
    Qt的WebEngineView加载网页时出现Error: WebGL is not supported
    一文搞懂shell脚本
  • 原文地址:https://blog.csdn.net/come_closer/article/details/127370137