在python中如何对文件夹内的所有图片进行切割

红心柚子 2019-06-06 10:47:07
我一改再改的代码,如下
from PIL import Image
import sys
import os
import cv2
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg

#遍历文件夹内所有的图片
def cv_imread(filePath):
cv_img = cv2.imdecode(np.fromfile(filePath, dtype=np.uint8), -1)
return cv_img


root="F:\\system\\Documents\\python_project\\shuzishibie\\images"
#image=[]
#label=[]
for dirpath, dirnames, filenames in os.walk(root):
for filepath in filenames:
#siwei=filepath[0:4]
srcImage = cv_imread(os.path.join(root,filepath))
#cv2.imshow("Src", srcImage)
#cv2.waitKey(0)


#切图
def cut_image(image):
width, height = image.size
item_width = int(width / 4)
box_list = []
# (left, upper, right, lower)
for i in range(0,4):#一重循环,生成张图片基于原图的位置
box = (i*item_width,0,(i+1)*item_width,height)
box_list.append(box)

image_list = [image.crop(box) for box in box_list]
return image_list

#保存
def save_images(image_list):
index = 1
for image in image_list:
image.save('./img/'+str(index) + '.png', 'PNG')
index += 1

if __name__ == '__main__':
image = Image.open(file_path)
#image.show()
image_list = cut_image(image)
save_images(image_list)
...全文
632 5 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
小学生5566 2019-10-07
  • 打赏
  • 举报
回复
引用 4 楼 惟愿莲心不染尘 的回复:
[quote=引用 2 楼 小学生5566 的回复:] 楼主,请问你这个程序跑的通嘛?我报错了FileNotFoundError: [Errno 2] No such file or directory: '2.png'
检查你的运行路径是否和lz一样,是否有代码中写死的目录[/quote] 这里的file_path也有问题吧? if __name__ == '__main__': image = Image.open(file_path) #image.show() image_list = cut_image(image) save_images(image_list)
????Robin 2019-10-03
  • 打赏
  • 举报
回复
楼主程序好像没法跑通。
  • 打赏
  • 举报
回复
引用 2 楼 小学生5566 的回复:
楼主,请问你这个程序跑的通嘛?我报错了FileNotFoundError: [Errno 2] No such file or directory: '2.png'
检查你的运行路径是否和lz一样,是否有代码中写死的目录
小学生5566 2019-09-29
  • 打赏
  • 举报
回复
楼主,请问你这个程序跑的通嘛?我报错了FileNotFoundError: [Errno 2] No such file or directory: '2.png'
红心柚子 2019-06-06
  • 打赏
  • 举报
回复
实现对图片的批量切割

37,743

社区成员

发帖
与我相关
我的任务
社区描述
JavaScript,VBScript,AngleScript,ActionScript,Shell,Perl,Ruby,Lua,Tcl,Scala,MaxScript 等脚本语言交流。
社区管理员
  • 脚本语言(Perl/Python)社区
  • WuKongSecurity@BOB
加入社区
  • 近7日
  • 近30日
  • 至今

试试用AI创作助手写篇文章吧