CIFAR10
CIFAR10 이미지를 사용하려 이미지를 다운받아 읽어봤는데,
plt.imshow(img.astype('uint8'))
아래와 같은 에러가 발생했다.
TypeError: Invalid shape (3072,) for image data
우선 CIFAR10은 채널마다 32 $\times$ 32 의 픽셀로 표현되어있는 이미지 자료이다. 때문에 32*32*3=3072의 값이 에러에 보인다.
Code
이 문제는 내가 받은 CIFAR10이 32 $\times$ 32 $\times$ 3 이런 모양이 아니라, 3 $\times$ 32 $\times$ 32의 모양으로 제공되기 때문에 발생한다. Torch에서도 이런 식으로 shape을 갖는다. 이 문제를 해결하고자 transpose라는 함수를 사용해 일반적인(?) 32 $\times$ 32 $\times$ 3 shape으로 이미지를 바꾸어 보았다.
Data Loading
CIFAR10 다운 받은걸 불러오는 과정.
files = glob.glob('./data/cifar-10-batches-py/data_batch_*')
train_xs = []
train_ys = []
for path in files:
train_batch = unpickle(path)
train_xs.append(train_batch['data'])
train_ys.append(train_batch['labels'])
X_train = np.concatenate(train_xs)
Y_train = np.concatenate(train_ys)
Function
Shape을 바꾸는 함수와, 바꾼걸 보여주는 함수. "transpse" 함수를 통해 shape 두번째와 세번째(각각 index 1과 2)를 첫번째와 두번째로 위치하도록 바꾸고, 첫번째(index 0)를 마지막으로 바꾸는 작업을 하도록 한다. 사실 "transpse"는 단순히 행렬을 전치해주는 함수인줄만 알았다, 그런데 알고보니 어려워 보이는 작업을 해주는 굉장히 간단하고 좋은 함수!
def CIFAR_img_reshape(img):
return img.reshape(3,32,32).transpose(1,2,0)
def CIFAR_img_show(img, reshaped = False, plt_show = True):
if reshaped:
plt.imshow(img.astype('uint8'))
else:
plt.imshow(CIFAR_img_reshape(img).astype('uint8'))
if plt_show:
plt.show()
Images
위의 함수 사용하여 CIFAR10 5개까지 보이기.
classes = ['plane', 'car', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck']
for vis_idx in range(5):
print(classes[Y_train[vis_idx]])
CIFAR_img_show(X_train[vis_idx])
...
이런식으로 shape을 변형하면 이미지 시각화가 가능해진다. 다른 이미지 자료를 보게될 때에 위와같은 에러가 발생하면, shape을 한번 확인해보자!
'정리 조금 > Codes' 카테고리의 다른 글
[Docker] Restart (0) | 2024.01.23 |
---|---|
[Python] Package Version Check (0) | 2023.12.11 |
[Python] Paramiko (0) | 2023.10.25 |
[html] Tistory hELLO Skin, 사이드바에 방명록 추가 (0) | 2023.10.24 |
[Python] Cytominer Import Error (0) | 2023.10.18 |