Python OpenCV图像指定区域裁剪的实现


Posted in Python onOctober 30, 2019

在工作中。在做数据集时,需要对图片进行处理,照相的图片我们只需要特定的部分,所以就想到裁剪一种所需的部分。当然若是图片有规律可循则使用opencv对其进行膨胀腐蚀等操作。这样更精准一些。

一、指定图像位置的裁剪处理

import os  
import cv2 
 
# 遍历指定目录,显示目录下的所有文件名
def CropImage4File(filepath,destpath):
  pathDir = os.listdir(filepath)  # 列出文件路径中的所有路径或文件
  for allDir in pathDir:
    child = os.path.join(filepath, allDir)
    dest = os.path.join(destpath,allDir)
    if os.path.isfile(child):
     image = cv2.imread(child) 
      sp = image.shape      #获取图像形状:返回【行数值,列数值】列表
      sz1 = sp[0]         #图像的高度(行 范围)
      sz2 = sp[1]         #图像的宽度(列 范围)
      #sz3 = sp[2]        #像素值由【RGB】三原色组成
      
      #你想对文件的操作
      a=int(sz1/2-64) # x start
      b=int(sz1/2+64) # x end
      c=int(sz2/2-64) # y start
      d=int(sz2/2+64) # y end
      cropImg = image[a:b,c:d]  #裁剪图像
      cv2.imwrite(dest,cropImg) #写入图像路径
      
if __name__ == '__main__':
  filepath ='F:\\\maomi'       #源图像
  destpath='F:\\maomi_resize'    # resized images saved here
  CropImage4File(filepath,destpath)

二、批量处理—指定图像位置的裁剪

我这个是用来截取发票的印章区域,用于图像分割(公司的数据集保密)

各位可以用自己的增值发票裁剪。适当的更改截取区域

"""
处理数据集 和 标签数据集的代码:(主要是对原始数据集裁剪)
  处理方式:分别处理
  注意修改 输入 输出目录 和 生成的文件名
  output_dir = "./label_temp"
  input_dir = "./label"
"""
import cv2
import os
import sys
import time


def get_img(input_dir):
  img_paths = []
  for (path,dirname,filenames) in os.walk(input_dir):
    for filename in filenames:
      img_paths.append(path+'/'+filename)
  print("img_paths:",img_paths)
  return img_paths


def cut_img(img_paths,output_dir):
  scale = len(img_paths)
  for i,img_path in enumerate(img_paths):
    a = "#"* int(i/1000)
    b = "."*(int(scale/1000)-int(i/1000))
    c = (i/scale)*100
    time.sleep(0.2)
    print('正在处理图像: %s' % img_path.split('/')[-1])
    img = cv2.imread(img_path)
    weight = img.shape[1]
    if weight>1600:             # 正常发票
      cropImg = img[50:200, 700:1500]  # 裁剪【y1,y2:x1,x2】
      #cropImg = cv2.resize(cropImg, None, fx=0.5, fy=0.5,
                 #interpolation=cv2.INTER_CUBIC) #缩小图像
      cv2.imwrite(output_dir + '/' + img_path.split('/')[-1], cropImg)
    else:                    # 卷帘发票
      cropImg_01 = img[30:150, 50:600]
      cv2.imwrite(output_dir + '/'+img_path.split('/')[-1], cropImg_01)
    print('{:^3.3f}%[{}>>{}]'.format(c,a,b))

if __name__ == '__main__':
  output_dir = "../img_cut"      # 保存截取的图像目录
  input_dir = "../img"        # 读取图片目录表
  img_paths = get_img(input_dir)
  print('图片获取完成 。。。!')
  cut_img(img_paths,output_dir)

三、多进程(加快处理)

#coding: utf-8
"""
采用多进程加快处理。添加了在读取图片时捕获异常,OpenCV对大分辨率或者tif格式图片支持不好
处理数据集 和 标签数据集的代码:(主要是对原始数据集裁剪)
  处理方式:分别处理
  注意修改 输入 输出目录 和 生成的文件名
  output_dir = "./label_temp"
  input_dir = "./label"
"""
import multiprocessing
import cv2
import os
import time


def get_img(input_dir):
  img_paths = []
  for (path,dirname,filenames) in os.walk(input_dir):
    for filename in filenames:
      img_paths.append(path+'/'+filename)
  print("img_paths:",img_paths)
  return img_paths


def cut_img(img_paths,output_dir):
  imread_failed = []
  try:
    img = cv2.imread(img_paths)
    height, weight = img.shape[:2]
    if (1.0 * height / weight) < 1.3:    # 正常发票
      cropImg = img[50:200, 700:1500]   # 裁剪【y1,y2:x1,x2】
      cv2.imwrite(output_dir + '/' + img_paths.split('/')[-1], cropImg)
    else:                  # 卷帘发票
      cropImg_01 = img[30:150, 50:600]
      cv2.imwrite(output_dir + '/' + img_paths.split('/')[-1], cropImg_01)
  except:
    imread_failed.append(img_paths)
  return imread_failed


def main(input_dir,output_dir):
  img_paths = get_img(input_dir)
  scale = len(img_paths)

  results = []
  pool = multiprocessing.Pool(processes = 4)
  for i,img_path in enumerate(img_paths):
    a = "#"* int(i/10)
    b = "."*(int(scale/10)-int(i/10))
    c = (i/scale)*100
    results.append(pool.apply_async(cut_img, (img_path,output_dir )))
    print('{:^3.3f}%[{}>>{}]'.format(c, a, b)) # 进度条(可用tqdm)
  pool.close()            # 调用join之前,先调用close函数,否则会出错。
  pool.join()             # join函数等待所有子进程结束
  for result in results:
    print('image read failed!:', result.get())
  print ("All done.")



if __name__ == "__main__":
  input_dir = "D:/image_person"    # 读取图片目录表
  output_dir = "D:/image_person_02"  # 保存截取的图像目录
  main(input_dir, output_dir)

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

Python 相关文章推荐
python使用正则表达式来获取文件名的前缀方法
Oct 21 Python
只需7行Python代码玩转微信自动聊天
Jan 27 Python
Python3.7 pyodbc完美配置访问access数据库
Oct 03 Python
使用 Python 处理3万多条数据只要几秒钟
Jan 19 Python
flask框架蓝图和子域名配置详解
Jan 25 Python
Python实现队列的方法示例小结【数组,链表】
Feb 22 Python
Python *args和**kwargs用法实例解析
Mar 02 Python
解析pip安装第三方库但PyCharm中却无法识别的问题及PyCharm安装第三方库的方法教程
Mar 10 Python
Python smtp邮件发送模块用法教程
Jun 15 Python
使用keras实现BiLSTM+CNN+CRF文字标记NER
Jun 29 Python
python time()的实例用法
Nov 03 Python
浅谈Python协程asyncio
Jun 20 Python
使用Python刷淘宝喵币(低阶入门版)
Oct 30 #Python
Python自动化完成tb喵币任务的操作方法
Oct 30 #Python
Flask框架 CSRF 保护实现方法详解
Oct 30 #Python
使用Python和OpenCV检测图像中的物体并将物体裁剪下来
Oct 30 #Python
python基于K-means聚类算法的图像分割
Oct 30 #Python
Python列表原理与用法详解【创建、元素增加、删除、访问、计数、切片、遍历等】
Oct 30 #Python
Python文件路径名的操作方法
Oct 30 #Python
You might like
十天学会php之第一天
2006/10/09 PHP
用ADODB来让PHP操作ACCESS数据库的方法
2006/12/31 PHP
jQuery EasyUI API 中文文档 - DateBox日期框
2011/10/15 PHP
php判断字符串在另一个字符串位置的方法
2014/02/27 PHP
jQuery 1.5.1 发布,全面支持IE9 修复大量bug
2011/02/26 Javascript
Javascript的时间戳和php的时间戳转换注意事项
2013/04/12 Javascript
Jquery:ajax实现翻页无刷新功能代码
2013/08/05 Javascript
js 事件截取enter按键页面提交事件示例代码
2014/03/04 Javascript
浅谈Javascript的静态属性和原型属性
2015/05/07 Javascript
手机端页面rem宽度自适应脚本
2015/05/20 Javascript
JS原型、原型链深入理解
2016/02/27 Javascript
仿百度换肤功能的简单实例代码
2016/07/11 Javascript
js 将图片连接转换成base64格式的简单实例
2016/08/10 Javascript
用jquery获取自定义的标签属性的值简单实例
2016/09/17 Javascript
基于JavaScript实现全选、不选和反选效果
2017/02/15 Javascript
Angular5升级RxJS到5.5.3报错:EmptyError: no elements in sequence的解决方法
2018/04/09 Javascript
Vue混入mixins滚动触底的方法
2019/11/22 Javascript
javascript History对象原理解析
2020/02/17 Javascript
JavaScript实现多个物体同时运动
2020/03/12 Javascript
解决nuxt页面中mounted、created、watch执行两遍的问题
2020/11/05 Javascript
Python登录注册验证功能实现
2018/06/18 Python
Python 调用PIL库失败的解决方法
2019/01/08 Python
Python面向对象程序设计之类的定义与继承简单示例
2019/03/18 Python
tensorflow 变长序列存储实例
2020/01/20 Python
纯CSS3实现圆角效果(含IE兼容解决方法)
2014/05/07 HTML / CSS
英国银首饰公司:e&e Jewellery
2021/02/11 全球购物
揠苗助长教学反思
2014/02/04 职场文书
大班上学期幼儿评语
2014/04/30 职场文书
党委班子剖析材料
2014/08/21 职场文书
小学生运动会报道稿
2014/09/12 职场文书
怀孕辞职信怎么写
2015/02/28 职场文书
任命书标准格式
2015/03/02 职场文书
2015年小学教科研工作总结
2015/07/20 职场文书
MySQL命令行操作时的编码问题详解
2021/04/14 MySQL
python中super()函数的理解与基本使用
2021/08/30 Python
十大最强格斗系宝可梦,超梦X仅排第十,第二最重格斗礼仪
2022/03/18 日漫