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

 更新时间:2019年10月30日 14:19:27   作者:SongpingWang  
这篇文章主要介绍了Python OpenCV图像指定区域裁剪的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

在工作中。在做数据集时,需要对图片进行处理,照相的图片我们只需要特定的部分,所以就想到裁剪一种所需的部分。当然若是图片有规律可循则使用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 tkiner实现 一个小小的图片翻页功能的示例代码

    python tkiner实现 一个小小的图片翻页功能的示例代码

    这篇文章主要介绍了python tkiner实现 一个小小的图片翻页功能,需要的朋友可以参考下
    2020-06-06
  • Python结合OpenCV和Pyzbar实现实时摄像头识别二维码

    Python结合OpenCV和Pyzbar实现实时摄像头识别二维码

    这篇文章主要为大家详细介绍了如何使用Python编程语言结合OpenCV和Pyzbar库来实时摄像头识别二维码,文中的示例代码讲解详细,需要的可以参考下
    2024-01-01
  • python3.6中@property装饰器的使用方法示例

    python3.6中@property装饰器的使用方法示例

    这篇文章主要介绍了python3.6中@property装饰器的使用方法,结合实例形式分析了python3.6中@property装饰器的功能、使用方法及相关操作注意事项,需要的朋友可以参考下
    2019-08-08
  • Python使用atexit模块实现Golang的defer功能

    Python使用atexit模块实现Golang的defer功能

    这篇文章主要为大家详细介绍了Python如何使用atexit模块实现Golang的defer功能,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下
    2024-04-04
  • 执行Python程序时模块报错问题

    执行Python程序时模块报错问题

    这篇文章主要介绍了执行Python程序时模块报错问题及解决方法,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2020-03-03
  • python3实现小球转动抽奖小游戏

    python3实现小球转动抽奖小游戏

    这篇文章主要为大家详细介绍了python3实现小球转动抽奖小游戏,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2019-05-05
  • Python3 读、写Excel文件的操作方法

    Python3 读、写Excel文件的操作方法

    这篇文章主要介绍了Python3 读、写Excel文件的操作方法,需要的朋友可以参考下
    2018-10-10
  • Python使用列表推导式快速生成列表

    Python使用列表推导式快速生成列表

    这篇文章主要介绍了Python使用列表推导式快速生成列表,列表推导式是Python构建列表list的一种快捷方式,可以使用简洁的代码就创建出一个列表,需要的朋友可以参考下
    2023-07-07
  • python实现图像自动Gamma校正方式

    python实现图像自动Gamma校正方式

    这篇文章主要介绍了python实现图像自动Gamma校正方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2023-10-10
  • python常用数据结构集合详解

    python常用数据结构集合详解

    这篇文章主要介绍了python常用数据结构集合详解,文章围绕主题展开详细的内容介绍,具有一定的参考价值,感兴趣的小伙伴可以参考一下,希望对你的学习有所帮助
    2022-08-08

最新评论