python使用opencv切割图片白边
作者:喝完这杯还有一箱 时间:2021-10-16 04:44:06
本文实例为大家分享了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))
原始图片:
结果:
来源:https://blog.csdn.net/qq_37049050/article/details/108116304
标签:python,切割图片
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
MySQL UPDATE时主键冲突引发的思考
2008-06-21 17:00:00
对python3.4 字符串转16进制的实例详解
2022-03-29 16:15:17
Python 爬虫的工具列表大全
2023-03-29 06:27:57
python实时检测键盘输入函数的示例
2023-01-27 19:19:28
PHP 危险函数全解析
2023-11-20 15:36:12
GoFrame框架gcache的缓存控制淘汰策略实践示例
2023-07-22 06:41:19
![](https://img.aspxhome.com/file/2023/8/97718_0s.png)
网页颜色变黑白CSS代码 适合所有类型网站
2010-04-21 10:37:00
Django 中使用日志的方法
2022-09-12 11:17:40
![](https://img.aspxhome.com/file/2023/3/101453_0s.png)
Python pandas轴旋转stack和unstack的使用说明
2021-08-10 21:18:34
![](https://img.aspxhome.com/file/2023/4/120904_0s.jpg)
python工具之清理 Markdown 中没有引用的图片
2022-02-14 11:44:39
![](https://img.aspxhome.com/file/2023/0/67300_0s.png)
python给视频添加背景音乐并改变音量的具体方法
2021-01-26 20:18:47
python 输出所有大小写字母的方法
2021-01-05 01:02:57
java JSP开发之Spring中Bean的使用
2023-06-16 07:35:08
![](https://img.aspxhome.com/file/2023/1/77461_0s.png)
JS中的THIS和WINDOW.EVENT.SRCELEMENT详解
2023-07-20 20:48:51
Php中文件下载功能实现超详细流程分析
2023-10-07 17:09:13
![](https://img.aspxhome.com/file/2023/2/55762_0s.png)
Python制作简易版小工具之计算天数的实现思路
2023-10-29 08:12:07
![](https://img.aspxhome.com/file/2023/4/91874_0s.png)
python将MongoDB里的ObjectId转换为时间戳的方法
2022-08-08 04:33:01
python flask实现分页的示例代码
2021-04-01 09:55:23
python time.sleep()是睡眠线程还是进程
2022-04-09 17:33:16
python 类的继承 实例方法.静态方法.类方法的代码解析
2021-12-19 14:19:34