Python中图像通用操作的实现代码

 更新时间:2023年07月03日 11:40:14   作者:fengbingchun  
这篇文章主要为大家详细介绍了Python中图像通用操作的实现,例如:图像旋转、图像缩放等,文中的示例代码讲解详细,需要的可以参考一下

平时经常会对一个目录下的图像做统一处理,如缩放、旋转等等,之前使用C++处理,有时不是很方便。发现使用Python比较简单,代码量又很少,在Anacanda下执行起来也比较方便。因此,打算在后面遇到图像的常规处理时都将其实现放入到同一个py文件中,用时可随时执行。

所有实现存放在OpenCV_Test/demo/Python的image_generic_operations.py文件中,目前实现的仅有:图像旋转(仅限90,180,270度)、图像缩放,后面会逐渐增加,实现代码如下:

import os
import sys
import cv2
from inspect import currentframe, getframeinfo
import argparse
 
def get_image_list(path, image_suffix):
    image_list = []
    for x in os.listdir(path):
        if x.endswith(image_suffix):
            image_list.append(path+"/"+x)
 
    return image_list
 
def get_image_name(image_name):
    pos = image_name.rfind("/")
    image_name = image_name[pos+1:]
 
    return image_name
 
def image_rotate_clockwise(image_list, degrees, result_path):
    print("image rotation ...")
    os.makedirs(result_path, exist_ok=True)
 
    if degrees == 90:
        rotate_code = cv2.ROTATE_90_CLOCKWISE
    elif degrees == 180:
        rotate_code = cv2.ROTATE_180
    elif degrees == 270:
        rotate_code = cv2.ROTATE_90_COUNTERCLOCKWISE
    else:
        raise Exception("Unsupported rotat degrees: {}, it only supports: clockwise 90, 180, 270; Error Line: {}".format(degrees, getframeinfo(currentframe()).lineno))
 
    for name in image_list:
        print(f"\t{name}")
        image_name = get_image_name(name)
        #print(f"image name:{image_name}"); sys.exit(1)
 
        mat = cv2.imread(name)
        mat = cv2.rotate(mat, rotateCode=rotate_code)
        cv2.imwrite(result_path+"/"+image_name, mat)
 
def image_resize(image_list, dst_width, dst_height, result_path):
    print("image resize ...")
    os.makedirs(result_path, exist_ok=True)
 
    mat = cv2.imread(image_list[0])
    h, w, _ = mat.shape
    if h > dst_width and w > dst_height:
        interpolation = cv2.INTER_AREA
    else:
        interpolation = cv2.INTER_CUBIC
 
    for name in image_list:
        print(f"\t{name}")
        image_name = get_image_name(name)
        #print(f"image name:{image_name}"); sys.exit(1)
 
        mat = cv2.imread(name)
        mat = cv2.resize(mat, (dst_width, dst_height), interpolation=interpolation)
        cv2.imwrite(result_path+"/"+image_name, mat)
 
def parse_args():
    parser = argparse.ArgumentParser(description="image generic operations", add_help=True)
 
    parser.add_argument("--image_src_path", required=True, type=str, help="the path of the image to be operated, for example: ../../test_images")
    parser.add_argument("--operation", required=True, type=str, choices=["rotate", "resize"], help="specifies the operation to take on the image")
    parser.add_argument("--image_dst_path", required=True, type=str, help="the path where the resulting image is saved, for example: ../../test_images/result")
 
    parser.add_argument("--degrees", default=90, type=int, choices=[90, 180, 270], help="the degrees by which the image is rotated clockwise")
 
    parser.add_argument("--width", default=256, type=int, help="the width of the image after scaling")
    parser.add_argument("--height", default=256, type=int, help="the height of the image after scaling")
 
    parser.add_argument("--image_suffix", default=".png", type=str, help="the suffix of the processed image")
    
    args = parser.parse_args()
    return args
 
if __name__ == "__main__":
    args = parse_args()
 
    image_list = get_image_list(args.image_src_path, args.image_suffix)
 
    if args.operation == "rotate":
        image_rotate_clockwise(image_list, args.degrees, args.image_dst_path)
 
    if args.operation == "resize":
        image_resize(image_list, args.width, args.height, args.image_dst_path)
 
    print("test finish")

使用如下所示:

GitHubhttps://github.com/fengbingchun/OpenCV_Test

到此这篇关于Python中图像通用操作的实现代码的文章就介绍到这了,更多相关Python图像操作内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • Python实现3行代码解简单的一元一次方程

    Python实现3行代码解简单的一元一次方程

    这篇文章主要介绍了Python实现3行代码解简单的一元一次方程,很适合Python初学者学习借鉴,需要的朋友可以参考下
    2014-08-08
  • Python装饰器语法糖

    Python装饰器语法糖

    今天小编就为大家分享一篇关于Python装饰器语法糖,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧
    2019-01-01
  • python制作定时发送信息脚本的实现思路

    python制作定时发送信息脚本的实现思路

    这篇文章主要介绍了python实现企业微信定时发送文本消息的实例代码,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2020-11-11
  • Python英文文本分词(无空格)模块wordninja的使用实例

    Python英文文本分词(无空格)模块wordninja的使用实例

    今天小编就为大家分享一篇关于Python英文文本分词(无空格)模块wordninja的使用实例,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧
    2019-02-02
  • python实现百万答题自动百度搜索答案

    python实现百万答题自动百度搜索答案

    这篇文章主要为大家详细介绍了python实现百万答题自动百度搜索答案,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2018-01-01
  • Python网络编程实战之爬虫技术入门与实践

    Python网络编程实战之爬虫技术入门与实践

    这篇文章主要介绍了Python网络编程实战之爬虫技术入门与实践,了解这些基础概念和原理将帮助您更好地理解网络爬虫的实现过程和技巧,需要的朋友可以参考下
    2023-04-04
  • python实现字符串字母大小写转换的几种方法

    python实现字符串字母大小写转换的几种方法

    本文主要介绍了python实现字符串字母大小写转换的几种方法,包括islower()、isupper()、istitle()、lower()、casefold()、upper()、capitalize()、title()和swapcase(),具有一定的参考价值,感兴趣的可以了解一下
    2025-03-03
  • 在Python下利用OpenCV来旋转图像的教程

    在Python下利用OpenCV来旋转图像的教程

    这篇文章主要介绍了在Python下利用OpenCV来旋转图像的教程,代码和核心的算法都非常简单,需要的朋友可以参考下
    2015-04-04
  • Python如何用字典完成匹配任务

    Python如何用字典完成匹配任务

    在生物信息学领域,经常需要根据基因名称匹配其对应的编号,本文介绍了一种通过字典进行基因名称与编号匹配的方法,首先定义一个空列表存储对应编号,对于字典中不存在的基因名称,其编号默认为0
    2024-09-09
  • 利用python如何在前程无忧高效投递简历

    利用python如何在前程无忧高效投递简历

    这篇文章主要给大家介绍了关于利用python如何在前程无忧高效投递简历的相关资料,文中通过示例代码介绍的非常详细,对大家学习或者使用python具有一定的参考学习价值,需要的朋友们下面来一起学习学习吧
    2019-05-05

最新评论