zoukankan      html  css  js  c++  java
  • Python + openCV 实现图像垂直投影和水平投影

    Python + openCV 实现图像垂直投影和水平投影

    1. 先将需要投影的图片转为灰度图,我写了两个函数,分别实现对图像进行垂直投影和水平投影;

    if __name__ == '__main__':
    
        img = cv2.imread('C:\Users\24493\Desktop\123.jpg')  
        cv2.imshow("image",img)
        GrayImage=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)  #将img图像转换为灰度图,输出为GrayImage
        getVProjection(GrayImage)  #调用getVProjection函数进行垂直投影
        getHProjection(GrayImage)  #调用getHProjection函数进行水平投影
        cv2.waitKey(0)  
        cv2.destroyAllWindows()

    2. 进行垂直投影,将传入的灰度图转为黑白二值图,统计出每列的黑色点,然后再将统计结果全部集中在底部显示

    def getVProjection(image):
        # 将image图像转为黑白二值图,ret接收当前的阈值,thresh1接收输出的二值图
        ret, thresh1 = cv2.threshold(image, 127, 255, cv2.THRESH_BINARY)  
        (h,w)=thresh1.shape #返回高和宽
        a = [0 for z in range(0, w)] #a = [0,0,0,...,0,0]初始化一个长度为w的数组,用于记录每一列的黑点个数  
         
        #记录每一列的波峰
        for j in range(0,w): #遍历一列 
            for i in range(0,h):  #遍历一行
                if  thresh1[i,j]==0:  #如果该点为黑点
                    a[j]+=1          #该列的计数器加一计数
                    thresh1[i,j]=255  #记录完后将其变为白色 
              
        for j  in range(0,w):  #遍历每一列
            for i in range((h-a[j]),h):  #从该列应该变黑的最顶部的点开始向最底部涂黑
                thresh1[i,j]=0   #涂黑
        
        cv2.imshow('Vimage',thresh1)

    3. 进行水平投影,将传入的灰度图转为黑白二值图,统计出每行的黑色点,然后再将统计结果全部集中在左边显示;

    def getHProjection(image):
        # 将image图像转为黑白二值图,ret接收当前的阈值,thresh1接收输出的二值图
        ret, thresh1 = cv2.threshold(image, 127, 255, cv2.THRESH_BINARY) 
        (h,w)=thresh1.shape #返回高和宽
        a = [0 for z in range(0, h)]  #a = [0,0,0,...,0,0]初始化一个长度为h的数组,用于记录每一行的黑点个数  
         
        #记录每一行的波峰
        for j in range(0,h): #遍历一行 
            for i in range(0,w):  #遍历一列
                if  thresh1[j,i]==0:  #如果该点为黑点
                    a[j]+=1          #该列的计数器加一计数
                    thresh1[j,i]=255  #记录完后将其变为白色 
              
        for j  in range(0,h):  #遍历每一行
            for i in range(a[j]):  #从该行顶部的点开始向右涂黑统计的黑点数
                thresh1[j,i]=0   #涂黑
        
        cv2.imshow('Himage',thresh1)

    以下图为例:

    原图:

    垂直投影为:

     水平投影为:

  • 相关阅读:
    PAT (Advanced Level) 1086. Tree Traversals Again (25)
    PAT (Advanced Level) 1085. Perfect Sequence (25)
    PAT (Advanced Level) 1084. Broken Keyboard (20)
    PAT (Advanced Level) 1083. List Grades (25)
    PAT (Advanced Level) 1082. Read Number in Chinese (25)
    HDU 4513 吉哥系列故事――完美队形II
    POJ Oulipo KMP 模板题
    POJ 3376 Finding Palindromes
    扩展KMP
    HDU 2289 Cup
  • 原文地址:https://www.cnblogs.com/mulin1999/p/12493867.html
Copyright © 2011-2022 走看看