콘솔워크

opencv 이미지 명암 무작위 설정 본문

프로그래밍/python

opencv 이미지 명암 무작위 설정

이휘재123 2022. 7. 11. 17:21
반응형
import os
import random
import numpy as np
import cv2


def image_convert_random(inpath, outpath):

    img = cv2.imread(inpath)

    random_color = list(np.random.choice(range(256), size=3))
    print(random_color)

    for x in range(0, img.shape[1]):
        for y in range(0, 20):
            img[y, x] = (random_color)
    img = img

    random_value = random.randrange(1, 41)
    print(random_value)

    mask = np.ones_like(img) * random_value
    light_img = cv2.add(img, mask)
    dark_img = cv2.subtract(img, mask)

    imgs = [light_img, dark_img]
    new_img = random.choice(imgs)

    try:
        os.remove(outpath)
    except:
        pass
    
    cv2.imwrite(outpath, new_img)


if __name__ == "__main__":

    indir = r'E:\Consolework\blog-crwal\image'
    file_name = 'test_img.jpg'
    inpath = indir + f'\\{file_name}'
    outpath = indir + f'\\convert_{file_name}'
    try:
        os.remove(outpath)
    except:
        pass
    image_convert_random(inpath, outpath)

이미지 최상단에 랜덤하게 색상을 입힌 후 명암을 조절한다.

명암 범위는 1부터 40까지 랜덤한 수치를 조절하고, 밝은 이미지와 어두운 이미지 2개를 생성해 둘 중 하나를 랜덤하게 선택한다.

 

pip install opencv-python

pip install numpy

설치 필요

반응형