当前位置: 首页 > article >正文

opencv:实现图像的自动裁剪与优化

随着计算机视觉技术的发展,图像处理已成为一项重要的技能。今天,我们将探讨如何使用Python中的OpenCV库来实现对图像的自动裁剪以及一些基本的图像优化技巧。我们的目标是对一张发票图片进行处理,使其更加清晰且便于阅读。

准备工作

首先,确保你的环境中已经安装了numpyopencv-python这两个库。如果没有安装,可以使用pip进行安装:

pip install numpy opencv-python

代码解析

1. 导入所需模块

我们从导入必要的模块开始:

import numpy as np
import cv2

2. 定义辅助函数

接着定义几个辅助函数,如显示图像、排序坐标点以及进行四点变换等。

def cv_show(name, img):
    cv2.imshow(name, img)
    cv2.waitKey(0)

def order_points(pts):
    rect = np.zeros((4,2),dtype = "float32")
    s = pts.sum(axis=1)
    rect[0] = pts[np.argmin(s)]
    rect[2] = pts[np.argmax(s)]
    diff = np.diff(pts, axis=1)
    rect[1] = pts[np.argmin(diff)]
    rect[3] = pts[np.argmax(diff)]
    return rect

def four_point_transform(image, pts):
    rect = order_points(pts)
    (tl, tr, br, bl) = rect
    widthA = np.sqrt(((br[0] - bl[0])**2) + ((br[1] - bl[1])**2))
    widthB = np.sqrt(((tr[0] - tl[0])**2) + ((tr[1] - tl[1])**2))
    maxWidth = max(int(widthA), int(widthB))
    heightA = np.sqrt(((tr[0] - br[0])**2) + ((tr[1] - br[1])**2))
    heightB = np.sqrt(((tl[0] - bl[0])**2) + ((tl[1] - bl[1])**2))
    maxHeight = max(int(heightA), int(heightB))
    dst = np.array([[0, 0], [maxWidth - 1, 0], [maxWidth - 1, maxHeight - 1], [0, maxHeight - 1]], dtype="float32")
    M = cv2.getPerspectiveTransform(rect, dst)
    warped = cv2.warpPerspective(image, M, (maxWidth, maxHeight))
    return warped

def resize(image, width=None, height=None, inter=cv2.INTER_AREA):
    dim = None
    (h, w) = image.shape[:2]
    if width is None and height is None:
        return image
    if width is None:
        r = height / float(h)
        dim = (int(w * r), height)
    else:
        r = width / float(w)
        dim = (width, int(h * r))
    resized = cv2.resize(image, dim, interpolation=inter)
    return resized

3. 处理图像

然后加载图像,并调整其大小以便处理:

image = cv2.imread('picture_video/fapiao.jpg')
ratio = image.shape[0] / 500.0
orig = image.copy()
image = resize(orig, height=500)

4. 轮廓检测与变换

接下来是轮廓检测,找到最大的轮廓,并对其进行透视变换:

gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
edged = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1]
cnts = cv2.findContours(edged.copy(), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)[1]
screenCnt = sorted(cnts, key=cv2.contourArea, reverse=True)[0]
peri = cv2.arcLength(screenCnt, True)
screenCnt = cv2.approxPolyDP(screenCnt, 0.02 * peri, True)
warped = four_point_transform(orig, screenCnt.reshape(4, 2) * ratio)

5. 最终处理

最后,对变换后的图像进行灰度化处理、阈值分割以及旋转等操作:

warped = cv2.cvtColor(warped, cv2.COLOR_BGR2GRAY)
ref = cv2.threshold(warped, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1]
kernel = np.ones((2, 2), np.uint8)
ref_new = cv2.morphologyEx(ref, cv2.MORPH_CLOSE, kernel)
rotated_image = cv2.rotate(ref_new, cv2.ROTATE_90_COUNTERCLOCKWISE)

6.输出结果

结论

以上就是利用Python和OpenCV实现图像自动裁剪的一个简单示例。这种方法可以广泛应用于各种需要图像预处理的场合,比如文档扫描、车牌识别等。当然,实际应用中可能还需要考虑更多细节来提高准确性和鲁棒性。希望这篇教程能够帮助到正在学习图像处理的你!


http://www.kler.cn/news/323826.html

相关文章:

  • Python中的机器学习:从入门到实战
  • GO入门核心基础
  • 【linux 多进程并发】linux下使用常见命令,来解析进程家族体系脉络
  • Java: 数据类型与变量和运算符
  • 网络管理:网络故障排查指南
  • 目前相对稳定的下载上传的方法(WebClient )(异步与进度)
  • MacOS Sequoia安装geant4.10.07
  • 20_BERT微调训练
  • 探索Python网络世界的利器:Requests-HTML库
  • Python自学查漏9.28
  • Spark 中 任务集 TaskSet 详解
  • 探索私有化聊天软件:即时通讯与音视频技术的结合
  • RSpec简析及应用案例
  • leetcode刷题day32|动态规划Part01(509. 斐波那契数、70. 爬楼梯、746. 使用最小花费爬楼梯)
  • uni-app进行微信小程序开发,快速上手
  • STM32 F1移植FATFS文件系统 USMART组件测试相关函数功能
  • 二、初步编写drf API
  • 太速科技-389-基于KU5P的双路100G光纤网络加速计算卡
  • linux系统的常用命令
  • 【系统规划与管理师】【案例分析】【考点】【答案篇】第10章 团队建设与管理
  • docker相关命令
  • 基于单片机的精确电压表DA-AD转换
  • 【笔记】神领物流day1.1.13前后端部署【未完】
  • JVM、JRE、JDK关系。HotSpot。JVM规范
  • 【R语言】fs 工具功能速查
  • 【项目经验分享】深度学习点云算法毕业设计项目案例定制
  • 【JavaEE】——内存可见性问题
  • 支付宝远程收款api之小荷包跳转码
  • 画两个数的平方和的曲线
  • ECharts图表图例3