문제 : 내가 작업한 음정 비교 모델에서 비교 결과물을 서버로 넘겨야한다. 넘길 것은 크게 두 가지이다.
그래서 파이썬으로 JSON 오브젝트 생성과 파일로 저장하는 법. pyplot.savefig을 사용한 이미지 저장을 시도해보았다.
먼저 나는 이미지와 json파일에 구별을 위해 이름에 생성시각 정보를 사용할 것이기 떄문에 현재시각을 datetime모듈로 가져왔다.
from datetime import datetime
current_time = datetime.now().strftime('%Y%m%d_%H%M%S') # 'YYYYMMDD_HHMMSS' 형식
일반적으로 import datetime만 보다가 from datetime import date time을 보니 뭔 차인가 싶어 알아보았다.
이유는 datetime 모듈에 datetime이라는 클래스가 있기 때문이다.
깨알지식으로 알아두자
import matplotlib.pyplot as plt
...
plt.savefig(f'sim_wave_{current_time}.png', dpi=300, facecolor='white', edgecolor='black',orientation='portrait', format='png', transparent=False, bbox_inches = 'tight', pad_inches=0.1)
나는 음정비교를 표현하기 위해 대표적인 파이썬의 데이터 분석 라이브러리인 matplotlib을 사용했다.
그중에서 주로 pyplot을 사용하고 plt라는 이름으로 바꿔주는게 관례라고 한다.
아무튼 이렇게 비교를 끝낸 이미지를 원하는 경로에 저장하고 싶은데, pyplot에는 해당 기능을 savefig라는 함수로 지원한다. 사용법을 알아보자.
인자가 좀 많긴 하지만 그래도 손쉽게 이미지 파일로 저장하는데 성공했다.
import json
json_object = {
"id":current_time,
"similarity":round(similarity, 2),
"worst_time":worst_time,
"best_time":best_time,
"time_length":time_length
}
# current_time -> pyplot이미지와 동일한 시간 변수 사용
file_name = f'sim_result_{current_time}.json'
file_path = f'./{file_name}'
with open(file_path, 'w') as json_file:
json.dump(json_object, json_file, indent=4) # indent 4 는 가독성을 위함.
파이썬에서 JSON 오브젝트는 위와 같이
먼저 JSON 형태의 딕셔너리(json_object)를 만들고 파일을 열어 json.dump(딕셔너리, 파일객체)를 사용해 저장할 수 있다.
빨리 넘기고 서버 작업을 돕자
참조
https://lifelong-education-dr-kim.tistory.com/entry/%ED%8C%8C%EC%9D%B4%EC%8D%AC-Matplotlib%EC%9D%98-%EC%9D%B4%EB%AF%B8%EC%A7%80-%EC%A0%80%EC%9E%A5-%EB%A9%94%EC%84%9C%EB%93%9C-savefig-%EC%82%AC%EC%9A%A9%ED%95%98%EA%B8%B0
https://wikidocs.net/126088