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求crc32值的方法
Oct 05 Python
在Python中操作列表之List.pop()方法的使用
May 21 Python
Python获取运行目录与当前脚本目录的方法
Jun 01 Python
Django1.9 加载通过ImageField上传的图片方法
May 25 Python
Python延时操作实现方法示例
Aug 14 Python
Python中Proxypool库的安装与配置
Oct 19 Python
对pandas中时间窗函数rolling的使用详解
Nov 28 Python
django最快程序开发流程详解
Jul 19 Python
python 多维高斯分布数据生成方式
Dec 09 Python
linux 下python多线程递归复制文件夹及文件夹中的文件
Jan 02 Python
pytorch 中forward 的用法与解释说明
Feb 26 Python
python实现图片九宫格分割的示例
Apr 25 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中url传递中文字符,特殊危险字符的解决方法
2013/08/17 PHP
Laravel模板引擎Blade中section的一些标签的区别介绍
2015/02/10 PHP
PHP数据库连接mysql与mysqli对比分析
2016/01/04 PHP
PHP实践教程之过滤、验证、转义与密码详解
2017/07/24 PHP
js 键盘记录实现(兼容FireFox和IE)
2010/02/07 Javascript
js中将字符串转换成json的三种方式
2011/01/12 Javascript
jquery创建表格(自动增加表格)代码分享
2013/12/25 Javascript
js和jquery使按钮失效为不可用状态的方法
2014/01/26 Javascript
JavaScript把数组作为堆栈使用的方法
2015/03/20 Javascript
纯js实现仿QQ邮箱弹出确认框
2015/04/29 Javascript
使用CSS+JavaScript或纯js实现半透明遮罩效果的实例分享
2016/05/09 Javascript
详解Javascript中的原型OOP
2016/10/12 Javascript
微信小程序获取用户openId的实现方法
2017/05/23 Javascript
JS中Safari浏览器中的Date
2017/07/17 Javascript
jQuery实现菜单栏导航效果
2017/08/15 jQuery
解决vue-cli3 使用子目录部署问题
2018/07/19 Javascript
Angular事件之不同组件间传递数据的方法
2018/11/15 Javascript
JS实现可切换图片的幻灯切换效果示例
2019/05/24 Javascript
详解node和ES6的模块导出与导入
2020/02/19 Javascript
浅谈Python实现贪心算法与活动安排问题
2017/12/19 Python
Python中pillow知识点学习
2018/04/30 Python
深入浅析python 中的匿名函数
2018/05/21 Python
Python基于pandas实现json格式转换成dataframe的方法
2018/06/22 Python
Python基于WordCloud制作词云图
2019/11/29 Python
PyCharm永久激活方式(推荐)
2020/09/22 Python
pycharm工具连接mysql数据库失败问题
2020/04/01 Python
pandas读取csv文件提示不存在的解决方法及原因分析
2020/04/21 Python
python连接mongodb数据库操作数据示例
2020/11/30 Python
CSS3 实用技巧:实现黑白图像效果示例代码
2013/07/11 HTML / CSS
如何用canvas实现在线签名的示例代码
2018/07/10 HTML / CSS
英国家居用品和家居装饰品购物网站:Cox & Cox
2019/08/25 全球购物
中层干部岗位职责
2013/12/18 职场文书
数控技术应用个人求职信范文
2014/02/03 职场文书
行政部工作岗位职责范本
2014/03/05 职场文书
2015年青年志愿者工作总结
2015/05/20 职场文书
python中的sys模块和os模块
2022/03/20 Python