Changyu Lee

Dev Log [03.05.25] : PyTorch Integer Type Conversion

Published at
2025/03/05
Last edited time
2025/03/06 05:45
Created
2025/03/05 06:32
Section
Dev Log
Status
Done
Series
Tags
Code
Trouble Shooting
AI summary
Keywords
Python
PyTorch
Language
KOR

Situation

ref_outer_list = [int((x - x.min()) / (x.max() - x.min())) * 255 for x in ref_outer_list] gen_outer_list = [int((x - x.min()) / (x.max() - x.min())) * 255 for x in gen_outer_list] ValueError: only one element tensors can be converted to Python scalars
Python
복사

Why?

오류의 원인은 int()를 사용하여 배열 전체가 아니라 개별 요소를 변환하려고 했기 때문임
x는 텐서이므로 .min(), .max()가 텐서 전체 값이 아닌, 텐서의 요소별 연산으로 처리돼야 함.
int((x - x.min()) / (x.max() - x.min())) * 255
Python
복사
x - x.min(): x가 텐서이므로 결과도 텐서 (스칼라 값 아님).
/ (x.max() - x.min()): 여전히 텐서.
int(...): 텐서는 스칼라 값이 아니므로 int()가 적용될 수 없음 → ValueError 발생.
해결책: int()를 사용하지 말고 .to(torch.uint8) 또는 .numpy().astype(np.uint8)를 사용해야 함.

수정 방법

int()는 개별 스칼라 값에만 적용할 수 있기 때문에, 텐서 전체를 정규화한 후 to(torch.uint8) 또는 .numpy().astype(np.uint8)을 사용하면 해결할 수 있음.

수정된 코드

python 복사편집 # 모든 값이 0~255 범위로 정규화되도록 변환 ref_outer_list = [(x - x.min()) / (x.max() - x.min()) * 255 for x in ref_outer_list] gen_outer_list = [(x - x.min()) / (x.max() - x.min()) * 255 for x in gen_outer_list] # uint8 타입으로 변환 (PIL이나 OpenCV에서 사용할 경우 필요) ref_outer_list = [x.to(torch.uint8) for x in ref_outer_list] gen_outer_list = [x.to(torch.uint8) for x in gen_outer_list]
Python
복사

또는 NumPy 배열로 변환하는 방법

만약 NumPy로 변환해서 사용하려면 .numpy().astype(np.uint8)를 사용할 수 있음.
python 복사편집 ref_outer_list = [(x - x.min()) / (x.max() - x.min()) * 255 for x in ref_outer_list] gen_outer_list = [(x - x.min()) / (x.max() - x.min()) * 255 for x in gen_outer_list] # NumPy 변환 후 uint8 형식으로 변환 ref_outer_list = [x.cpu().numpy().astype(np.uint8) for x in ref_outer_list] gen_outer_list = [x.cpu().numpy().astype(np.uint8) for x in gen_outer_list]
Python
복사

Conclusion

1.
PIL이나 OpenCV에서 사용하려면: .to(torch.uint8) 또는 .numpy().astype(np.uint8) 변환 필요.
2.
int()는 전체 텐서가 아닌, 개별 요소에 적용해야 하므로 사용하면 안 됨.