박민혀기

Guide for using Google Drive API on RPi 본문

Research

Guide for using Google Drive API on RPi

박민혀기 2024. 6. 12. 09:36

Hardware/Software Environment

Processor : RaspberryPi3, 4

Camera : Raspberry Pi Camera(B) Rev 2.0

Language : Python

Library : OpenCV, Google Client Library

 

Flow

구글 드라이버를 사용하기 위해 사용자 동의가 필요하다.

프로그램에서 OAuth 동의서를 사용자에게 요청하고 사용자가 동의하게 되면 프로그램에게 동의서(동의 정보)를 전달하게 된다. 프로그램은 동의서를 구글에게 전달해 API 사용을 허가받게 되고, 그 후에 구글 API를 사용할 수 있게 된다.

추가 자세한 내용은 Google Cloud Create 부분에서 설명

 

Google Cloud Create

플리케이션과 동의 화면, API를 관리하는 프로젝트를 생성한다.

자세한 설명은 유튜브 설명을 따라 하면 된다.(1, 2편으로 나눠져 있다.)

중간에 json 파일을 다운로드하는 과정이 있는데 잘 보관하고 있어야 한다.(접속, 사용에 필요한 키)

이 json 파일의 파일명을 token.json으로 변경하는 게 아래 실습 코드를 사용하는 데 도움이 된다.

1편 : https://www.youtube.com/watch?v=A05rjn6x4vY

2편 : https://www.youtube.com/watch?v=1mFOa8OsYbQ

 

Python을 활용하여 Google Driver API 사용하기

우선 Python으로 사용하려면 Google Client Library 설치해야 한다.

pip install google-api-python-client google-auth-httplib2 google-auth-oauthlib

 

만약 다음과 같은 에러가 발생할 경우 가상환경을 생성하여 설치하면 된다.

error: externally-managed-environment

x This environment is externally managed
>>> To install Python packages system-wide, try apt install
    python3-xyz, where xyz is the package you are trying to
    install.
    
    If you wish to install a non-Debian-packaged Python package,
    create a virtual environment using python3 -m venv path/to/venv.
    Then use path/to/venv/bin/python and path/to/venv/bin/pip. Make
    sure you have python3-full installed.
    
    For more information visit http://rptl.io/venv

note: If you believe this is a mistake, please contact your Python installation or OS distribution provider. You can override this, at the risk of breaking your Python installation or OS, by passing --break-system-packages.
hint: See PEP 668 for the detailed specification.

 

OpenCV install Guide

프로젝트 진행을 위해 OpenCV를 사용하였다. (이미 OpenCV가 설치되어 있다면 다음 설치 가이드로 이동)

아래 Bash 스크립트를 실행하여 opencv-python 설치

!/bin/bash

echo "Installing required packages..."
sudo apt-get install -y build-essential cmake pkg-config
sudo apt-get install -y libjpeg-dev libtiff5-dev libjasper-dev libpng-dev
sudo apt-get install -y libavcodec-dev libavformat-dev libswscale-dev libv4l-dev
sudo apt-get install -y libxvidcore-dev libx264-dev
sudo apt-get install -y libfontconfig1-dev libcairo2-dev
sudo apt-get install -y libgdk-pixbuf2.0-dev libpango1.0-dev
sudo apt-get install -y libgtk2.0-dev libgtk-3-dev
sudo apt-get install -y libatlas-base-dev gfortran
sudo apt-get install -y python3-dev

echo "Installing pip and numpy..."
sudo apt-get install -y python3-pip
pip3 install numpy

echo "Installing OpenCV..."
pip3 install opencv-python

echo "Verifying OpenCV installation..."
python3 - <<EOF
import cv2
print("OpenCV version:", cv2.__version__)
EOF

echo "Installation complete!"

 

스크립트 파일 생성

nano install_opencv.sh

 

실행 권한 부여

chmod +x install_opencv.sh

 

스크립트 실행

./install_opencv.sh

 

스크립트 실행 결과가 다음과 같이 출력되면 정상적으로 설치 완료

OpenCV version: 4.5.1
Installation complete!

 

코드 동작 설명

아래는 코드 동작 전 코드 진행 알고리즘에 대해 설명하였다.

Goolgle API 사용을 위해 토큰을 사용하여 Google에 접속 →

OpenCV 활용하여 카메라 연결 →

카메라에서 촬영된 이미지 로컬 저장(저장 파일명은 Target.jpg로 다음에 업로드될 이미지이다.)  →

저장된 이미지를 Google Drive로 업로드(업로드 때 파일명은 001.jpg부터 차례로 숫자가 증가하여 업로드) →

ESC 키를 눌러 프로그램 종료

 

Testing

실행을 위해서는 Google Cloud Create 과정에서 저장되어 있던 json 파일(토큰)과 아래 소스코드만 같은 폴더에 있으면 된다.  (소스코드에서 DownloadImg 함수는 사용하지 않음)

만약 json파일명을 바꾸지 않았다면 json 파일의 파일명을 token.json으로 변경!!

(소스코드에서 token.json 파일명으로 불러옴)

from __future__ import print_function
import cv2
import os.path
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow

###Link Google Drive###
def AccessGoogleDrive():
	SCOPES = ['https://www.googleapis.com/auth/drive']
	creds = None

	if os.path.exists('token.json'):
		creds = Credentials.from_authorized_user_file('token.json', SCOPES)
	if not creds or not creds.valid:
		if creds and creds.expired and creds.refresh_token:
			creds.refresh(Request())
		else:
			flow = InstalledAppFlow.from_client_secrets_file('client_secret.json', SCOPES)
			creds = flow.run_local_server(port=0)

		with open('token.json', 'w') as token:
			token.write(creds.to_json())

	return creds

###Upload###
from googleapiclient.discovery import build
from googleapiclient.http import MediaFileUpload

def UploadImg(creds, fileName):
	service = build('drive', 'v3', credentials=creds)

	file_metadata = {'name': fileName}
	media = MediaFileUpload('Target.jpg', mimetype='image/jpg')

	file = service.files().create(body=file_metadata, media_body=media, fields='id').execute()
	print(F'File ID: {file.get("id")}')

###Download###
def DownloadImg():
	import io
	from googleapiclient.http import MediaIoBaseDownload

	file_id = '12AKMzbjceoM6fQhvsS1Uuz4PeNxh1MwR'
	request = service.files().get_media(fileId=file_id)
	file = io.BytesIO()
	downloader = MediaIoBaseDownload(file, request)
	done = False

	while done is False:
		status, done = downloader.next_chunk()
		print(F'Download{int(status.progress() * 100)}.')

	with open('savefile.png', 'wb') as f:
		f.write(file.getvalue())

creds = AccessGoogleDrive()

cap = cv2.VideoCapture(0)
if not cap.isOpened():
	print("Could't find or open camera")
	exit()

interval = 10
img_index = 1

while True:
	ret, frame = cap.read()
	if not ret:
		print("Could't find or open frame")
		break

	cv2.imwrite('Target.jpg', frame)
	cv2.waitKey(1)

	img_name = f"{img_index:03d}.jpg"
	UploadImg(creds, img_name)
	print(f"Save image : {img_name}")
	cv2.waitKey(1)

	img_index +=1

	cv2.imshow('frame', frame)
	if cv2.waitKey(interval * 1000) & 0xFF == 27:
		break

cap.release()
cv2.destroyAllWindows()

실행화면

 

Conclusion

이번 포스팅에서는 Python을 이용하여 Google 드라이브에 접속하고 업로드하는 부분을 다루었고, API 사용에 전체적인 구조를 알 수 있었다.또한 라즈베리파이 3, 4모델 둘 다 테스트해 본 결과 두 모델 모두 정상적으로 동작하는 것을 확인하였다.

다음 실험에서는 업로드 과정에서 Google Drive 상에 현재 시간으로 폴더를 생성한 후 그 폴더에 데이터를 저장하고, 반대로 Download 하여 이미지 데이터를 처리하는 부분을 실험할 예정이다.

 

 

 

'Research' 카테고리의 다른 글

SAM2(Segmentation Anything Model) by Meta on RPi5  (0) 2024.08.13
Guide for using Google Drive API on RPi(2)  (0) 2024.06.12
OpenAI gymnasium install  (0) 2024.04.15
PyTorch & CUDA Install  (0) 2024.04.15
Work & Research balance  (0) 2024.01.05