批量对图片处理:对图像进行色度饱和度亮度(HSV)调整

如果想对图像进行批量的处理:

1.修改图像的原始地址(original_images_path)和转换后的地址(combined_images_path

2.修改函数augment_hsv形参中的对应的 hgain、 sgain、 vgain即可

 

# -*- coding: utf-8 -*-

import numpy as np
import cv2
import os
from PIL import Image


# 原始地址和转换后的地址
original_images_path = r'E:\Pychram_program\cv2\original_pic\val'
combined_images_path = r'E:\Pychram_program\cv2\change\val'


# 进行色调饱和度亮度调整
def augment_hsv(img, hgain=0.0143, sgain=0.491, vgain=0.533):
    r = np.random.uniform(-1, 1, 3) * [hgain, sgain, vgain] + 1  # random gains
    hue, sat, val = cv2.split(cv2.cvtColor(img, cv2.COLOR_BGR2HSV))
    dtype = img.dtype  # uint8

    x = np.arange(0, 256, dtype=np.int16)
    lut_hue = ((x * r[0]) % 180).astype(dtype)
    lut_sat = np.clip(x * r[1], 0, 255).astype(dtype)
    lut_val = np.clip(x * r[2], 0, 255).astype(dtype)

    img_hsv = cv2.merge((cv2.LUT(hue, lut_hue), cv2.LUT(sat, lut_sat), cv2.LUT(val, lut_val))).astype(dtype)
    cv2.cvtColor(img_hsv, cv2.COLOR_HSV2BGR, dst=img)  # no return needed


# 寻找原始地址中的图像数据
def find_images(path):
    result = []
    for filename in os.listdir(path):
        _, ext = os.path.splitext(filename.lower())
        if ext == ".jpg" or ext == ".png":
            result.append(os.path.join(path, filename))
            pass
        pass
    result.sort()
    return result


if __name__ == '__main__':
    original_images = find_images(original_images_path)

    for image_path in original_images:

        img_name = image_path[len(original_images_path):]
        original = Image.open(image_path)
        original_img = cv2.imread(image_path)
        change_img = cv2.resize(original_img, (640, 640))
        augment_hsv(change_img)
        cv2.imwrite(combined_images_path + img_name, change_img)

你可能感兴趣的:(图像处理,python,计算机视觉)