python使用opencv切割图片白边

 更新时间:2021年09月05日 15:41:07   作者:喝完这杯还有一箱  
这篇文章主要为大家详细介绍了python使用opencv切割图片的白边,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一

本文实例为大家分享了python使用opencv切割图片白边的具体代码,可以横切和竖切,供大家参考,具体内容如下

废话不多说直接上码,分享使人进步:

from PIL import Image
from itertools import groupby
import cv2
import datetime
import os
 
# from core.rabbitmq import MessageQueue
 
THRESHOLD_VALUE = 230  # 二值化时的阈值
PRETREATMENT_FILE = 'hq'  # 横切时临时保存的文件夹
W = 540  # 最小宽度
H = 960  # 最小高度
 
 
class Pretreatment(object):
    __doc__ = "图片横向切割"
 
    def __init__(self, path, save_path, min_size=960):
        self.x = 0
        self.y = 0
        self.img_section = []
        self.continuity_position = []
        self.path = path
        self.save_path = save_path
        self.img_obj = None
        self.min_size = min_size
        self.mkdir(self.save_path)
        self.file_name = self.path.split('/')[-1]
 
    def get_continuity_position_new(self):
        img = cv2.imread(self.path)
        gray_image = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        ret, thresh1 = cv2.threshold(gray_image, THRESHOLD_VALUE, 255, cv2.THRESH_BINARY)
 
        width = img.shape[1]
        height = img.shape[0]
        self.x = width
        self.y = height
        for i in range(0, height):
            if thresh1[i].sum() != 255 * width:
                self.continuity_position.append(i)
 
    def filter_rule(self):
        if self.y < self.min_size:
            return True
 
    def mkdir(self, path):
        if not os.path.exists(path):
            os.makedirs(path)
 
    def get_section(self):
        # 获取区间
        for k, g in groupby(enumerate(self.continuity_position), lambda x: x[1] - x[0]):
            l1 = [j for i, j in g]  # 连续数字的列表
            if len(l1) > 1:
                self.img_section.append([min(l1), max(l1)])
 
    def split_img(self):
        print(self.img_section)
        for k, s in enumerate(self.img_section):
            if s:
                if not self.img_obj:
                    self.img_obj = Image.open(self.path)
 
                if self.x < W:
                    return
                if s[1] - s[0] < H:
                    return
                cropped = self.img_obj.crop((0, s[0], self.x, s[1]))  # (left, upper, right, lower)
                self.mkdir(os.path.join(self.save_path, PRETREATMENT_FILE))
                cropped.save(os.path.join(self.save_path, PRETREATMENT_FILE, f"hq_{k}_{self.file_name}"))
 
    def remove_raw_data(self):
        os.remove(self.path)
 
    def main(self):
        # v2
        try:
            self.get_continuity_position_new()
            self.filter_rule()
            self.get_section()
            self.split_img()
        except Exception as e:
            print(self.file_name)
            print(e)
        finally:
            if self.img_obj:
                self.img_obj.close()
 
 
class Longitudinal(Pretreatment):
    def get_continuity_position_new(self):
        print(self.path)
        img = cv2.imread(self.path)
        gray_image = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        ret, thresh1 = cv2.threshold(gray_image, THRESHOLD_VALUE, 255, cv2.THRESH_BINARY)
 
        width = img.shape[1]
        height = img.shape[0]
        print(width, height)
        self.x = width
        self.y = height
        for i in range(0, width):
            if thresh1[:, i].sum() != 255 * height:
                self.continuity_position.append(i)
 
    def split_img(self):
        print(self.img_section)
        for k, s in enumerate(self.img_section):
            if s:
                if not self.img_obj:
                    self.img_obj = Image.open(self.path)
                if self.y < H:
                    return
                if s[1] - s[0] < W:
                    return
                cropped = self.img_obj.crop((s[0], 0, s[1], self.y))  # (left, upper, right, lower)
                cropped.save(os.path.join(self.save_path, f"{k}_{self.file_name}"))
 
 
def main(path, save_path):
    starttime = datetime.datetime.now()
    a = Pretreatment(path=path, save_path=save_path)
    a.main()
    for root, dirs, files in os.walk(os.path.join(save_path, PRETREATMENT_FILE)):
        for i in files:
            b = Longitudinal(path=os.path.join(save_path, PRETREATMENT_FILE, i), save_path=save_path)
            b.main()
            os.remove(os.path.join(save_path, PRETREATMENT_FILE, i))
    endtime = datetime.datetime.now()
    print(f'耗时:{(endtime - starttime)}')
 
 
if __name__ == '__main__':
    path = '你图片存放的路径'
    save_path = '要保存的路径'
    for _, _, files in os.walk(path):
        for i in files:
            main(path=os.path.join(path, i), save_path=save_path)
    os.rmdir(os.path.join(save_path, PRETREATMENT_FILE))

原始图片:

结果:

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

相关文章

  • Python reflect单例模式反射各个函数

    Python reflect单例模式反射各个函数

    这篇文章主要介绍了Python reflect单例模式反射各个函数,文章围绕主题展开详细的内容介绍,具有一定的参考价值需要的小伙伴可以参考一下
    2022-06-06
  • python中with用法讲解

    python中with用法讲解

    在本篇文章里小编给大家整理的是关于python中with用法讲解内容,有需要的朋友们可以参考下。
    2020-02-02
  • python列表中删除重复元素的三种方法

    python列表中删除重复元素的三种方法

    本文主要介绍了python列表中删除重复元素的三种方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2025-01-01
  • Python动态导入模块的方法实例分析

    Python动态导入模块的方法实例分析

    这篇文章主要介绍了Python动态导入模块的方法,结合实例形式较为详细的分析了Python动态导入系统模块、自定义模块以及模块列表的相关操作技巧,需要的朋友可以参考下
    2018-06-06
  • python验证身份证信息实例代码

    python验证身份证信息实例代码

    这篇文章主要介绍了python验证身份证信息的方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2019-05-05
  • Python cookbook(字符串与文本)针对任意多的分隔符拆分字符串操作示例

    Python cookbook(字符串与文本)针对任意多的分隔符拆分字符串操作示例

    这篇文章主要介绍了Python cookbook(字符串与文本)针对任意多的分隔符拆分字符串操作,结合实例形式分析了Python使用split()及正则表达式进行字符串拆分操作相关实现技巧,需要的朋友可以参考下
    2018-04-04
  • 对Python中GIL(全局解释器锁)的一点理解浅析

    对Python中GIL(全局解释器锁)的一点理解浅析

    首先需要明确的一点是GIL并不是Python的特性,它是在实现Python解析器(CPython)时所引入的一个概念,下面这篇文章主要给大家介绍了关于对Python中GIL的一点理解,文中通过示例代码介绍的非常详细,需要的朋友可以参考下
    2022-05-05
  • 详解Python中import模块导入的实现原理

    详解Python中import模块导入的实现原理

    这篇文章主要给大家介绍了Python中import模块导入的实现原理,主要从什么是模块,import搜索路径以及导入原理这三个方面给大家介绍,感兴趣的小伙伴跟着小编一起来看看吧
    2023-08-08
  • Python格式化输出的具体实现

    Python格式化输出的具体实现

    本文主要介绍了Python格式化输出的具体实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2022-06-06
  • python的random模块及加权随机算法的python实现方法

    python的random模块及加权随机算法的python实现方法

    下面小编就为大家带来一篇python的random模块及加权随机算法的python实现方法。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-01-01

最新评论