파이썬(Python)/opencv

[Python]OpenCV 이미지 파일 저장, 파일 크기 확인하기(JPG, PNG, TIFF)

끄적끄적아무거나 2022. 2. 10. 18:35
반응형

 

목차

     

     

    OpenCV imwrite 함수

     

    파이썬의 OpenCV에서 이미지 파일을 열거나 만든 다음에 파일을 다른이름으로 저장할 때 imwrite함수를 사용합니다. imwrite 함수의 Syntax는 아래와 같습니다. 

     

    cv2.imwrite(filename, img, [parameters])

     

    • filename : 저장하고자 하는 파일명을 입력합니다. 확장자명까지 추가해서 이미지 파일(Image file)의 종류도 결정 합니다. 
    • img : 저장하고자 하는 이미지를 입력 합니다.
    • parameters : 이미지 파일 포맷에 맞춰서 압축, 화질들을 결정하는 파라미터 값을 설정할 수 있습니다. 

     

     

     

    OpenCV 이미지 파일 저장, 파일 크기 확인하기(JPG, PNG, TIFF)

     

    예제를 통해 이미지 파일을 읽고 파일을 jpg, png, tiff로 저장하고 각 파일의 크기 변화를 확인해 보겠습니다. 

     

    예제 코드>>

    import cv2
    import os
    
    img_ori = cv2.imread('flowers.png')
    
    cv2.imwrite("flowers_copy.png", img_ori)
    cv2.imwrite("flowers.jpg", img_ori)
    cv2.imwrite("flowers.tiff", img_ori)
    
    file_size = os.path.getsize('flowers.png')
    print("Original png file size : " + str(file_size) + " Bytes")
    file_size = os.path.getsize('flowers_copy.png')
    print("Copied png file size : " + str(file_size) + " Bytes")
    file_size = os.path.getsize('flowers.jpg')
    print("Copied jpg file size : " + str(file_size) + " Bytes")
    file_size = os.path.getsize('flowers.tiff')
    print("Copied tiff file size : " + str(file_size) + " Bytes")

    4번 라인: 미리 저장한 flowers.png 파일을 imread 함수를 사용해서 읽어 옵니다.

    6~8번 라인 : imwrite 함수를 사용해서 읽어온 파일을 다른 형태의 파일명으로 저장합니다.

    10~17번 라인 : 저장된 파일과 원본 파일의 크기를 불러 옵니다.

     

     

    결과>>

    Original png file size : 447973 Bytes
    Copied png file size : 422394 Bytes
    Copied jpg file size : 200725 Bytes
    Copied tiff file size : 497390 Bytes

     

    tiff의 경우 원본 이미지 파일보다 파일 크기가 증가하였습니다.

    반응형