前言

使用opencv对图像进行操作,要求:(1)定位银行票据的四条边,然后旋正。(2)根据版面分析,分割出小写金额区域。

图像校正

首先是对图像的校正

  1. 读取图片
  2. 对图片二值化
  3. 进行边缘检测
  4. 对边缘的进行霍夫曼变换
  5. 将变换结果从极坐标空间投影到笛卡尔坐标得到倾斜角
  6. 根据倾斜角对主体校正
import os
import cv2
import math
import numpy as np
from scipy import ndimage filepath = './task1-misc/'
filename = 'bank-bill.bmp'
filename_correct = 'bank-bill-correct.png' def image_correction(input_path: str, output_path: str) -> bool:
# 读取图像
img = cv2.imread(input_path)
# 二值化
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
# 边缘检测
edges = cv2.Canny(gray,50,150,apertureSize = 3)
#霍夫变换
lines = cv2.HoughLines(edges,1,np.pi/180,0)
for rho,theta in lines[0]:
a = np.cos(theta) # 将极坐标转换为直角坐标
b = np.sin(theta)
x0 = a*rho
y0 = b*rho
x1 = int(x0 + 1000*(-b)) # 保证端点够远能够覆盖整个图像
y1 = int(y0 + 1000 * a)
x2 = int(x0 - 1000*(-b))
y2 = int(y0 - 1000 * a)
if x1 == x2 or y1 == y2:
continue
t = float(y2-y1)/(x2-x1)
# 得到角度后将角度范围调整至-45至45度之间
rotate_angle = math.degrees(math.atan(t))
if rotate_angle > 45:
rotate_angle = -90 + rotate_angle
elif rotate_angle < -45:
rotate_angle = 90 + rotate_angle
# 图像根据角度进行校正
rotate_img = ndimage.rotate(img, rotate_angle)
# 在图中画出线
cv2.line(img, (x1, y1), (x2, y2), (0, 0, 255), 2)
cv2.imwrite(filepath + 'marked-'+filename_correct, img)
# 输出图像
cv2.imwrite(output_path, rotate_img)
return True input_path = filepath + filename
output_path = filepath + filename_correct
if image_correction(input_path, output_path):
print("角度校正成功")

图(左)中的红线斜率和偏置是经过霍夫变换并进行极坐标转换后得到,后续将根据这条线进行角度的校正,校正后的结果如图(右)所示。


为了便于后续操作,我们选择将背景去掉,保存为.png图片。

filename_clear = 'bank-bill-clear.png'
# 去除背景
def remove_background(input_path: str, output_path: str) -> bool:
# 读取图像
img = cv2.imread(input_path, cv2.IMREAD_UNCHANGED) # 检查是否已经具有 alpha 通道,如果没有则创建一个
if img.shape[2] == 3:
alpha_channel = np.ones_like(img[:, :, 0], dtype=img.dtype) * 255
img = np.dstack((img, alpha_channel)) # 提取图像的 alpha 通道(透明度)
alpha_channel = img[:, :, 3] # 将白色或黑色(背景)的像素设置为透明
alpha_channel[(img[:, :, :3] == [255, 255, 255]).all(axis=2)] = 0
alpha_channel[(img[:, :, :3] == [0, 0, 0]).all(axis=2)] = 0
# 保存为带有透明通道的 PNG 图像
cv2.imwrite(output_path, img)
return True
input_path = filepath + filename_correct
output_path = filepath + filename_clear
if remove_background(input_path, output_path):
print("去除背景成功")

版面分析与分割金额区域

使用opencv对图像进行版面分析得到表格线的投影。

def detectTable(img, save_path):

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

    thresh_img = cv2.adaptiveThreshold(~gray_img,255,cv2.ADAPTIVE_THRESH_MEAN_C,cv2.THRESH_BINARY,15,-2)

    h_img = thresh_img.copy()
v_img = thresh_img.copy()
scale = 20
h_size = int(h_img.shape[1]/scale) h_structure = cv2.getStructuringElement(cv2.MORPH_RECT,(h_size,1)) # 形态学因子
h_erode_img = cv2.erode(h_img,h_structure,1) h_dilate_img = cv2.dilate(h_erode_img,h_structure,1)
# cv2.imshow("h_erode",h_dilate_img)
v_size = int(v_img.shape[0] / scale) v_structure = cv2.getStructuringElement(cv2.MORPH_RECT, (1, v_size)) # 形态学因子
v_erode_img = cv2.erode(v_img, v_structure, 1)
v_dilate_img = cv2.dilate(v_erode_img, v_structure, 1) mask_img = h_dilate_img+v_dilate_img
joints_img = cv2.bitwise_and(h_dilate_img,v_dilate_img)
joints_img = cv2.dilate(joints_img,None,iterations=3)
cv2.imwrite(os.path.join(save_path, "joints.png"),joints_img)
cv2.imwrite(os.path.join(save_path, "mask.png"), mask_img)
return joints_img, mask_img img = cv2.imread(os.path.join(filepath, filename_clear))
_, mask_img = detectTable(img, save_path=filepath)

投影得到两张图,一张表示交叉点的投影,另一张表示表格线的投影,如下图所示,后续的边缘检测我们将用到右侧的图。

def find_bound(img):

    # 查找图像中的轮廓
contours, _ = cv2.findContours(img, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_TC89_L1) # 遍历所有轮廓
site = []
for contour in contours:
# 计算边界矩形
x, y, w, h = cv2.boundingRect(contour)
if 20 < w < 35 and 20 <h < 35:
site.append((x, y, w, h),)
site.sort(key=lambda x: (x[0], x[1], x[2], x[3]))
return site site = find_bound(mask_img)

mask.png,使用边缘检测,获取各个边缘的位置信息,根据所得的位置信息,在bank-bill-clear.png(对原图矫正角度并去除背景)中裁剪,并限制裁剪的图像块长宽在(20,35)的区间范围(实际尝试中并不能检测到金额区域的完整边缘,而是金额区域每个方形的边缘,(20,35)表示每个方形的长宽区间范围,如下图所示)。

save_path = './task1-result'
if os.path.exists(save_path) is False:
os.makedirs(save_path) for i in site:
x, y, w, h = i
cv2.imwrite(os.path.join(save_path, f"{x}-{y}-{w}-{h}.png"), img[y:y+h, x:x+w])
(x0, y0, w, h) = site[0]
x, y = x0+(w+2)*11, y0+h*2
cv2.imwrite(os.path.join(save_path, "res.png"), img[y0:y, x0:x])

对裁剪的图像块的坐标进行排序,推测出完整金额的具体位置,并再次裁剪,得到最后结果

运行环境

numpy==1.26.2
opencv_contrib_python==4.6.0.66
opencv_python==4.6.0.66
scipy==1.11.4

参考文献

  1. Python对图像进行倾斜校正
  2. 深入理解OpenCV中的(row,col)和(x,y)
  3. 版面分析那些事

基于OpenCV-Python的图像位置校正和版面分析的更多相关文章

  1. Opencv python图像处理-图像相似度计算

    一.相关概念 一般我们人区分谁是谁,给物品分类,都是通过各种特征去辨别的,比如黑长直.大白腿.樱桃唇.瓜子脸.王麻子脸上有麻子,隔壁老王和儿子很像,但是儿子下巴涨了一颗痣和他妈一模一样,让你确定这是你 ...

  2. Java基于opencv—透视变换矫正图像

    很多时候我们拍摄的照片都会产生一点畸变的,就像下面的这张图 虽然不是很明显,但还是有一点畸变的,而我们要做的就是把它变成下面的这张图 效果看起来并不是很好,主要是四个顶点找的不准确,会有一些偏差,而且 ...

  3. 基于opencv+python的二维码识别

    花了2天时间终于把二维码识别做出来了,不过效果一般,后面会应用在ROS辅助定位上,废话少说先上图: 具体过程参考了这位大神的博客:http://blog.csdn.net/qq_25491201/ar ...

  4. opencv python:图像直方图 histogram

    直接用matplotlib画出直方图 def plot_demo(image): plt.hist(image.ravel(), 256, [0, 256]) # image.ravel()将图像展开 ...

  5. openCV—Python(5)—— 图像几何变换

    一.函数简单介绍 1.warpAffine-图像放射变换(平移.旋转.缩放) 函数原型:warpAffine(src, M, dsize, dst=None, flags=None, borderMo ...

  6. opencv python:图像梯度

    一阶导数与Soble算子 二阶导数与拉普拉斯算子 图像边缘: Soble算子: 二阶导数: 拉普拉斯算子: import cv2 as cv import numpy as np # 图像梯度(由x, ...

  7. opencv python:图像金字塔

    图像金字塔原理 expand = 扩大+卷积 拉普拉斯金字塔 PyrDown:降采样 PyrUp:还原 example import cv2 as cv import numpy as np # 图像 ...

  8. opencv python:图像二值化

    import cv2 as cv import numpy as np import matplotlib.pyplot as plt # 二值图像就是将灰度图转化成黑白图,没有灰,在一个值之前为黑, ...

  9. opencv+python实现图像锐化

    突然发现网上都是些太繁琐的方法,我就找opencv锐化函数咋这么墨迹. 直接上代码: kernel = np.array([[0, -1, 0], [-1, 5, -1], [0, -1, 0]], ...

  10. Python图像处理丨基于OpenCV和像素处理的图像灰度化处理

    摘要:本篇文章讲解图像灰度化处理的知识,结合OpenCV调用cv2.cvtColor()函数实现图像灰度操作,使用像素处理方法对图像进行灰度化处理. 本文分享自华为云社区<[Python图像处理 ...

随机推荐

  1. nvm:npm的包管理器

    NVM: npm的包管理器 其实许久前就像写这个模块了,只是之前使用后又搁置了,今天下项目时node版本不一致,才想起记录 nvm下载地址: Releases · coreybutler/nvm-wi ...

  2. Nginx 代理后,打开新窗口,报404,开发环境下没有问题

    解决办法: router/index.js文件中, 将 router 的 mode 属性设置为 hash,不要使用 history

  3. HTTP Headers Content-Type 详解

    https://www.cnblogs.com/whosmeya/p/14315632.html

  4. FZU 2232

    ***题意:求最大匹配是否为n 今天突然想起来吧模板改一下,然而自己得想法不对,WA了有十多次吧,看了一下题解,不需要改,套上模板就行*** #include<stdio.h> #incl ...

  5. 码农的转型之路-IoTBrowser(物联网浏览器)雏形上线

    消失了半个月闭门造轮子去了,最近干了几件大事: 1.工控盒子,win10系统长时间跑物联网服务测试.运行快2周了,稳定性效果还满意,除了windows自动更新重启了一次. 2 .接触了一些新概念MQT ...

  6. [转帖]oracle ZHS16GBK的数据库导入到字符集为AL32UTF8的数据库(转载+自己经验总结)

    字符集子集向其超集转换是可行的,如此例 ZHS16GBK转换为AL32UTF8. 导出使用的字符集将会记录在导出文件中,当文件导入时,将会检查导出时使用的字符集设置,如果这个字符集不同于导入客户端的N ...

  7. [转帖].NET Framework 中的传输层安全性 (TLS) 最佳做法

    https://learn.microsoft.com/zh-cn/dotnet/framework/network-programming/tls 传输层安全性 (TLS) 协议是一个行业标准,旨在 ...

  8. [转帖]Unicode与utf的前世今生

    https://www.cnblogs.com/naodong/p/12742987.html 历史上存在两个独立的尝试创立单一字符集的组织,即 国际标准化组织(ISO)于1984年创建的通用字符集( ...

  9. [转帖]如何监控Redis性能指标(译)

    Redis给人的印象是简单.很快,但是不代表它不需要关注它的性能指标,此文简单地介绍了一部分Redis性能指标.翻译过程中加入了自己延伸的一些疑问信息,仍然还有一些东西没有完全弄明白.原文中Metri ...

  10. [转帖]是什么让 Redis“气急败坏”回击:13 年来,总有人想替 Redis 换套新架构

    https://www.infoq.cn/article/AlF5NIhHdskayl0MTyQG 回击就代表输了?! 今年年中,一位前谷歌.前亚马逊的工程师推出了他创作的开源内存数据缓存系统 Dra ...