图片分割和图片合成(大图切割成小图,python代码)

 

 

本文实现内容如下:

宽图切割成四个短图,当然代码的切割功能不限于此。

分割前:

 

 分割后:

 

 

pip3 install opencv-python==4.5.5.62
pip3 install tqdm

--------------------- imread读取路径中不能带中文字符--------------------------------

处理单张图片:

import cv2
import numpy as np
import os

pic_path = r"D:\test\before\0.jpg"  # 分割的图片的位置
pic_target = r'D:\test\after\\'  # 分割后的图片保存的文件夹
if not os.path.exists(pic_target):  # 判断是否存在文件夹如果不存在则创建为文件夹
    os.makedirs(pic_target)
# 要分割后的尺寸
cut_width = 600
cut_length = 900
# 读取要分割的图片,以及其尺寸等数据
picture = cv2.imread(pic_path)
# --------------------- imread读取路径中不能带中文字符--------------------------------
(width, length, depth) = picture.shape
# 预处理生成0矩阵
pic = np.zeros((cut_width, cut_length, depth))
# 计算可以划分的横纵的个数
num_width = int(width / cut_width)
num_length = int(length / cut_length)
# for循环迭代生成
for i in range(0, num_width):
    for j in range(0, num_length):
        pic = picture[i * cut_width: (i + 1) * cut_width, j * cut_length: (j + 1) * cut_length, :]
        result_path = pic_target + '{}_{}.jpg'.format(i + 1, j + 1)
        cv2.imwrite(result_path, pic)

print("done!!!")

global D:\a\opencv-python\opencv-python\opencv\modules\imgcodecs\src\loadsave.cpp (239) cv::findDecoder imread_('D:\000datasets\

AttributeError: 'NoneType' object has no attribute 'shape'

错误原因:imread读取路径中不能带中文字符

处理文件夹图片:

一个循环遍历即可。

 

 

import cv2
import numpy as np
import os
from tqdm import tqdm

pic_folder = r"D:\test\before"  # 分割的图片的位置
pic_target = r'D:\test\after\\'  # 分割后的图片保存的文件夹
if not os.path.exists(pic_target):  # 判断是否存在文件夹如果不存在则创建为文件夹
    os.makedirs(pic_target)
for item in tqdm(os.listdir(pic_folder)):
    pic_path = os.path.join(pic_folder,item)
    # print(pic_path)

    # 要分割后的尺寸
    cut_width = 600
    cut_length = 900
    # 读取要分割的图片,以及其尺寸等数据
    picture = cv2.imread(pic_path)
    # --------------------- imread读取路径中不能带中文字符--------------------------------
    (width, length, depth) = picture.shape
    # 预处理生成0矩阵
    pic = np.zeros((cut_width, cut_length, depth))
    # 计算可以划分的横纵的个数
    num_width = int(width / cut_width)
    num_length = int(length / cut_length)
    # for循环迭代生成
    for i in range(0, num_width):
        for j in range(0, num_length):
            pic = picture[i * cut_width: (i + 1) * cut_width, j * cut_length: (j + 1) * cut_length, :]
            result_path = pic_target + '{}_{}.jpg'.format(item[:-4], j+1)
            cv2.imwrite(result_path, pic)
print("done!!!")

参考文章链接:

图片分割和图片合成(大图切割成小图,python代码)

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

CCCHHH333

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

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

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

打赏作者

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

抵扣说明:

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

余额充值