Python opencv图像投影

题目描述
利用opencv或其他工具编写程序实现图像的水平投影、垂直投影。


实现过程

import cv2  
from pathlib import Path

gray_img = cv2.imread(str(Path(Path.cwd().parent, 'test.png')), 0)
cv2.imshow('img1', gray_img)

# 水平投影
_, thresh1 = cv2.threshold(gray_img, 130, 255, cv2.THRESH_BINARY)    # 阈值分割,得到二值图
high, width = thresh1.shape    # 返回高和宽
# 初始化一个跟图像高一样长度的数组,用于记录每一行的黑点个数
arr1 = [0 for n in range(0, high)] 
for row in range(0, high):    # 遍历每行
    for column in range(0, width):    # 遍历每列
        if  thresh1[row, column] == 0:    # 判断该点是否为黑点,0代表黑点
            arr1[row] += 1    # 该行的计数器加一
            thresh1[row, column] = 255    # 将其改为白点,即等于255         
for row  in range(0, high):    # 遍历每一行
    for column in range(0, arr1[row]):    # 从该行应该变黑的最左边的点开始向最右边的点设置黑点
        thresh1[row, column] = 0    # 设置黑点
cv2.imshow('img2', thresh1)

# 垂直投影
_, thresh2 = cv2.threshold(gray_img, 130, 255, cv2.THRESH_BINARY)
high, width = thresh2.shape    # 返回高和宽
# 初始化一个跟图像宽一样长度的数组,用于记录每一列的黑点个数
arr2 = [0 for n in range(0, width)]
for column in range(0, width):    # 遍历每一列 
    for row in range(0, high):    # 遍历每一行
        if  thresh2[row, column] == 0:    # 判断该点是否为黑点,0代表是黑点
            arr2[column] += 1     # 该列的计数器加1
            thresh2[row, column] = 255    # 记录完后将其变为白色,即等于255    
for column in range(0, width):    # 遍历每一列
    for row in range(high - arr2[column], high):    # 从该列应该变黑的最顶部的开始向最底部设为黑点
        thresh2[row, column] = 0    # 设为黑点        
cv2.imshow('img3', thresh2)

cv2.waitKey(0)  
cv2.destroyAllWindows()

运行结果
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Dream丶Killer

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值