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 getopt 参数处理小示例
Jun 09 Python
python读文件逐行处理的示例代码分享
Dec 27 Python
Python使用Flask框架获取当前查询参数的方法
Mar 21 Python
在Python中使用Neo4j数据库的教程
Apr 16 Python
pandas.DataFrame 根据条件新建列并赋值的方法
Apr 08 Python
Python多进程原理与用法分析
Aug 21 Python
python 实现将txt文件多行合并为一行并将中间的空格去掉方法
Dec 20 Python
Python hexstring-list-str之间的转换方法
Jun 12 Python
python实现布隆过滤器及原理解析
Dec 08 Python
Django 设置多环境配置文件载入问题
Feb 25 Python
Python 给下载文件显示进度条和下载时间的实现
Apr 02 Python
全网最细 Python 格式化输出用法讲解(推荐)
Jan 18 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 和 MYSQL
2006/10/09 PHP
php代码收集表单内容并写入文件的代码
2012/01/29 PHP
PHP实现的获取文件mimes类型工具类示例
2018/04/08 PHP
js传值 判断
2006/10/26 Javascript
Javascript 两个窗体之间传值实现代码
2009/09/25 Javascript
用jQuery打造TabPanel效果代码
2010/05/22 Javascript
javascript中字符串拼接需注意的问题
2010/07/13 Javascript
jquery退出each循环的写法
2014/02/26 Javascript
两种方法实现在HTML页面加载完毕后运行某个js
2014/06/16 Javascript
js css 实现遮罩层覆盖其他页面元素附图
2014/09/22 Javascript
JavaScript中的无阻塞加载性能优化方案
2014/10/10 Javascript
jQuery通过控制节点实现仅在前台通过get方法完成参数传递
2015/02/02 Javascript
jQuery给多个不同元素添加class样式的方法
2015/03/26 Javascript
BOM系列第一篇之定时器setTimeout和setInterval
2016/08/17 Javascript
HTML5 实现的一个俄罗斯方块实例代码
2016/09/19 Javascript
基于HTML5+JS实现本地图片裁剪并上传功能
2017/03/24 Javascript
angular学习之ngRoute路由机制
2017/04/12 Javascript
浅谈es6语法 (Proxy和Reflect的对比)
2017/10/24 Javascript
webpack 从指定入口文件中提取公共文件的方法
2018/11/13 Javascript
在Express中提供静态文件的实现方法
2019/10/17 Javascript
如何基于layui的laytpl实现数据绑定的示例代码
2020/04/10 Javascript
python爬取淘宝商品销量信息
2018/11/16 Python
Python程序包的构建和发布过程示例详解
2019/06/09 Python
Pandas分组与排序的实现
2019/07/23 Python
如何在VSCode上轻松舒适的配置Python的方法步骤
2019/10/28 Python
python 字典item与iteritems的区别详解
2020/04/25 Python
python实现猜数游戏(保存游戏记录)
2020/06/22 Python
python如何停止递归
2020/09/09 Python
谷歌浏览器小字体处理方案即12px以下字体
2013/12/17 HTML / CSS
Vilebrequin欧洲官网:法国豪华泳装品牌(男士沙滩裤)
2018/04/14 全球购物
世界上最大的艺术和工艺用品商店:MisterArt.com
2018/07/13 全球购物
Steiff台湾官网:德国金耳釦泰迪熊
2019/12/26 全球购物
家庭财产分割协议书范本
2014/11/24 职场文书
高三数学复习备考教学反思
2016/02/18 职场文书
Django利用AJAX技术实现博文实时搜索
2021/05/06 Python
SpringBoot详解整合Redis缓存方法
2022/07/15 Java/Android