728x90

Pillow 모듈을 이용하여 완전 검정/완전 흰색 이미지를 탐지하는 기법을 소개한다.

 

1. Create sample images.

from pathlib import Path
from PIL import Image

# Create directory
sample_dir = "./sample"
Path(sample_dir).mkdir(exist_ok=True)

# Create solid(color) image function 
def create_solid_image(save_path:str, width=24, height=24, color=(255, 255, 255)):
    try:
        new_image = Image.new("RGB", (width, height), color)
        new_image.save(save_path)
        new_image.close()
        return True
    except Exception as e:
        raise e 

black_image_src = sample_dir + "/" + "black.png"    
white_image_src = sample_dir + "/" + "white.png"

def create_sample_image():
    w = 400
    h = 400
    
    # 올블랙 이미지 생성
    color = (0, 0, 0)
    create_solid_image(black_image_src, w, h, color)

	# 올화이트 이미지 생성
    color = (255, 255, 255)
    create_solid_image(white_image_src, w, h, color)

create_sample_image()

# pixabay
#normal_image_url = "https://cdn.pixabay.com/photo/2023/05/02/05/00/tulips-7964346_1280.jpg"
#normal_image_src = wget.download(normal_image_url, out=sample_dir)
#normal_image_src

normal_image_src = sample_dir+"/tulips-7964346_1280.webp"

2. Check images.

from PIL import Image

def check_image(image_src)->str:
    NORMAL="normal"
    COMPLETELY_BLACK="black"
    COMPLETELY_WHITE="white"

    with Image.open(image_src) as im:
        # Convert Grayscale.
        grayscale = im.convert(mode="L")
        # getextrema 이미지에 포함하는 있는 컬러의 극값(extremum) 튜플 형태(min, max) 로 반환한다.
        ext = grayscale.getextrema()
        if (ext==(0, 0)):
            return COMPLETELY_BLACK
        elif (ext==(255, 255)):
            return COMPLETELY_WHITE
        else:
            return NORMAL

# 샘플 이미지 경로 지정.
sample_dir = "./sample"
black_image_src = sample_dir + "/" + "black.png"    
white_image_src = sample_dir + "/" + "white.png"
normal_image_src = sample_dir+"/tulips-7964346_1280.webp"

# 이미지 체크
print(f"{normal_image_src} checked : {check_image(normal_image_src)}" )
print(f"{black_image_src} checked : {check_image(black_image_src)}" )
print(f"{white_image_src} checked : {check_image(white_image_src)}" )

 

728x90
  • 네이버 블러그 공유하기
  • 네이버 밴드에 공유하기
  • 페이스북 공유하기
  • 카카오스토리 공유하기
반응형