图像通用操作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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python中,有多个库可以用于图像处理,其中包括scipy.ndimageOpenCV和PIL。scipy.ndimage库中的morphology模块可以实现形态学操作,而measurements模块可以用于二值图像的计数和度量功能。下面是一个使用scipy.ndimage库进行图像处理的示例代码: ```python from scipy.ndimage import measurements, morphology from PIL import Image import numpy as np # 载入图像,然后使用阈值化操作,以保证处理的图像为二值图像 im = np.array(Image.open('houses.png').convert('L')) im = 1 * (im < 128) # 使用measurements模块计算图像中的对象数量 labels, nbr_objects = measurements.label(im) print("Number of objects:", nbr_objects) ``` 另外,OpenCV是一个跨平台的开源图像处理库,它提供了很多通用图像处理和计算机视觉算法。你可以使用OpenCV来进行各种图像处理操作,例如图像滤波、边缘检测、图像分割等。下面是一个使用OpenCV进行图像处理的示例代码: ```python import cv2 # 读取图像 img = cv2.imread('car.jpg') # 打印图像信息 print(img.shape, img.dtype) # 对图像进行处理,例如调整大小、保存图像等 resized_img = cv2.resize(img, (800, 600)) cv2.imwrite('car_2.jpg', resized_img) cv2.imshow('Image', resized_img) cv2.waitKey(0) cv2.destroyAllWindows() ``` 此外,PIL库也可以用于图像处理。你可以使用PIL库读取图像、调整图像大小、保存图像等。下面是一个使用PIL库进行图像处理的示例代码: ```python from PIL import Image # 读取图像 img = Image.open('car.jpg') # 打印图像信息 print(img.size) # 对图像进行处理,例如调整大小、保存图像等 resized_img = img.resize((800, 600), Image.ANTIALIAS) resized_img.save('car_2.jpg') resized_img.show() ``` 综上所述,你可以根据具体的需求选择合适的库来进行图像处理。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值