opencv_python realizes batch image color transformation, which can be used for data enhancement

Transformation principle : HSV

Algorithm flow : cv2 reads the rgb value of the picture in the file in turn, and then converts it to hsv, and changes the color of the picture by changing the h (namely hue) value in hsv to generate multiple color-transformed pictures (which can be used for data enhancement).

Not much nonsense, the code (remember to change the path of the two folders to your own input and output paths when you use it, and the pictures under the folder are named in the order of 1, 2, 3,...):

import cv2

num = 0 #读取的图片序号 
num_max = 7 #图片总数量
hue_change = 5 #色调改变值 步长
count = 0 #记录每张图片生成的数量

while 1:
    img_name = 'C:/Users/hq/Desktop/person_img/img/%s.jpg' % str(num+1)
    img=cv2.imread(img_name, cv2.IMREAD_COLOR)    # 打开文件
     
    # 通过cv2.cvtColor把图像从BGR转换到HSV
    img_hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
     

    turn_green_hsv = img_hsv.copy()
    # 色调hue变化范围5——50
    for i in range(1,11):
        turn_green_hsv[:, :, 0] = (turn_green_hsv[:, :, 0] + hue_change*i) % 180
        turn_green_img = cv2.cvtColor(turn_green_hsv, cv2.COLOR_HSV2BGR)

        cv2.imwrite('C:/Users/hq/Desktop/person_img/color_change_img/%s_%s.jpg'%(str(num+1), str(count+1)), turn_green_img)
        print("successfully save %s_%s pic" %(str(num+1), str(count+1)))
        count += 1

    if num == num_max - 1:
        exit(0)
    
    count = 0
    num += 1

operation result:


This is the picture under the author's input folder:
Insert picture description here
This is the result of the output folder:
Insert picture description here
Note: The author's preset tone conversion value is 5~50, and readers can set the step length and range of h according to their needs.

Guess you like

Origin blog.csdn.net/weixin_44414948/article/details/106077973