Deep Learning/Semantic Segmentation

Semantic Segmentation 작업에서 label 저장하는 법

jstar0525 2021. 12. 2. 18:15
반응형

 

Semantic Segmentation 이해


Semantic Segmentation 작업에 관련된 데이터 형식은 아래와 같습니다.

 

Data input : 이미지

           shape : HxWx3(RGB) or HxWx1(흑백)

 

Data label :

            shape : HxWx1

            각 픽셀은 각 class에 해당하는 정수, eg. [0, 1, 2, 3 ...]

            파일 형식 : png - 주의; 만약 jpg 형식은 손실 압축으로 인하여 label의 정보가 변경됨

 

Model Output : 

            추가적으로, 딥러닝 모델의 출력은 아래와 같이 one-hot encoding된 형태로 나오며,

            channel 방향으로 argmax를 통하여 위와 같은 label과 비교할 수 있습니다.

            (또는 역으로 label을 one-hot encoding 형태로 변환)

 

 

 

Label 저장하기


pillow 라이브러리를 이용하여

Label을 저장하기 위한 방법을 알아보겠습니다.

 

 

먼저, 간단하게 label을 만들어보겠습니다.

import numpy as np
from PIL import Image
import matplotlib.pyplot as plt

label = np.random.randint(3, size=(10,10), dtype=np.uint8)

print(label)

plt.imshow(label, cmap = 'gray')
plt.show()
[[0 1 2 0 2 1 0 1 2 2]
 [2 0 2 0 2 0 1 2 0 1]
 [1 2 1 0 1 1 0 1 0 0]
 [0 1 2 0 0 2 2 2 0 2]
 [2 0 2 1 0 1 0 2 2 0]
 [1 2 2 2 2 0 1 0 0 0]
 [1 0 2 0 0 0 2 0 2 1]
 [2 0 0 0 2 0 0 0 0 0]
 [1 2 2 1 0 0 2 0 2 1]
 [2 2 2 0 0 1 0 0 1 1]]

 

그리고, 그냥 이미지와 같이 저장하면

어떠한 문제가 생기는지 알아보겠습니다.

 

png = Image.fromarray(label).convert('P')
png.save('label.png')

위와 같이 저장한 파일에서는 아무것도 보이지 않습니다.

 

실제 파일에는 각 label이 잘 저장되어 있지만,

흑백 이미지는 0~255의 값에 따라 intensity가 정해지기 때문입니다.

 

따라서, 위 문제를 해결하기 위해서

indexed image를 만들기 위하여 putpalette를 사용합니다.

 

palette = [0,0,0,255,0,0,0,128,0]

png = Image.fromarray(label).convert('P')
png.putpalette(palette)
png.save('label.png')

 

palette에 대하여 설명하자면

  • 0번 label : [0,0,0]
  • 1번 label : [255,0,0,]
  • 2번 label : [0,128,0]

으로 구성된 연속된 list로, 각 label에 대하여 RGB 값을 나타냅니다.

 

그리고 해당 label을 다시 읽었을 경우,

정상적으로 값이 잘 나타나는 것을 확인할 수 있습니다.

 

read = np.asarray(Image.open('./label.png'))
print(read)
[[0 1 2 0 2 1 0 1 2 2]
 [2 0 2 0 2 0 1 2 0 1]
 [1 2 1 0 1 1 0 1 0 0]
 [0 1 2 0 0 2 2 2 0 2]
 [2 0 2 1 0 1 0 2 2 0]
 [1 2 2 2 2 0 1 0 0 0]
 [1 0 2 0 0 0 2 0 2 1]
 [2 0 0 0 2 0 0 0 0 0]
 [1 2 2 1 0 0 2 0 2 1]
 [2 2 2 0 0 1 0 0 1 1]]

 

 

결론


1. label 저장 시 png 파일 형식으로 저장

2. 바로 시각적으로 확인하기 위해서는 indexed image 형태로 저장

 

 

 

ref.

https://medium.com/neuralworks/semantic-segmentation-label-image-%EC%83%9D%EC%84%B1%ED%95%98%EA%B8%B0-521aa7f6371c

 

Semantic Segmentation — Label Image 생성하기

시작하기에 앞서, Semantic Segmentation Task가 정확히 어떤 Task인지 알아야 합니다. Semantic Segmentation Task의 경우, 전체 이미지에 대해 각각의 픽셀이 어느 Label(=Category)에 속하는지 분류하는 문제입니다

medium.com

https://www.jeremyjordan.me/semantic-segmentation/

 

An overview of semantic image segmentation.

In this post, I'll discuss how to use convolutional neural networks for the task of semantic image segmentation. Image segmentation is a computer vision task in which we label specific regions of an image according to what's being shown. "What's in this im

www.jeremyjordan.me

 

반응형