반드시 라즈베리파이를 종료하고 전원 케이블까지 뺀 다음에 연결한다!
카메라를 사용하기 위해 라즈베리파이 설정을 수정한다.
sudo apt-get update
sudo raspi-config
# Interface Options -> Legacy Camera Enable
# Advanced Options -> Glamor Enable
# reboot
sudo reboot
Picamera2 설치
공식 document : https://pypi.org/project/picamera2/0.2.2/
sudo apt install -y python3-libcamera python3-kms++
sudo apt install -y python3-pyqt5 python3-prctl libatlas-base-dev ffmpeg python3-pip
pip3 install numpy --upgrade
pip3 install picamera2[gui]
# If you do not want the GUI dependencies, use
# sudo apt install -y python3-libcamera python3-kms++
# sudo apt install -y python3-prctl libatlas-base-dev ffmpeg libopenjp2-7 python3-pip
# pip3 install numpy --upgrade
# pip3 install picamera2
libcamera 설치
참고 블로그 : https://dev-russel.tistory.com/83
streaming.py
io.BufferedIOBase
를 상속받은 StreamingOutput 객체(output
)를 하나 만든다. server.BaseHTTPRequestHandler
를 상속받은 StreamingHandler 객체는 do_GET
메서드를 통해 get 요청을 처리한다./
로 들어오면 /index.html
로 리다이렉트한다./index.html
에 대한 리소스 요청이 들어오면 미리 정의해둔 PAGE
의 html을 보여준다.PAGE
는 stream.mpjpg
라는 이미지 파일을 보여주는데, 이 파일에 대한 리소스 요청도 do_GET
에서 처리한다. StreamingServer
는 핸들러와 주소를 설정해주는 객체이다. import io
import logging
import socketserver
from http import server
from threading import Condition
class StreamingOutput(io.BufferedIOBase):
def __init__(self):
self.frame = None
self.condition = Condition()
def write(self, buf):
with self.condition:
self.frame = buf
self.condition.notify_all()
class StreamingHandler(server.BaseHTTPRequestHandler):
PAGE = """\
<html>
<head>
<title>picamera2 MJPEG streaming demo</title>
</head>
<body>
<h1>Front Camera Streaming</h1>
<img src="stream.mjpg" width="auto" height="auto" />
</body>
</html>
"""
def do_GET(self):
global output
if self.path == '/':
self.send_response(301)
self.send_header('Location', '/index.html')
self.end_headers()
elif self.path == '/index.html':
content = self.PAGE.encode('utf-8')
self.send_response(200)
self.send_header('Content-Type', 'text/html')
self.send_header('Content-Length', len(content))
self.end_headers()
self.wfile.write(content)
elif self.path == '/stream.mjpg':
self.send_response(200)
self.send_header('Age', 0)
self.send_header('Cache-Control', 'no-cache, private')
self.send_header('Pragma', 'no-cache')
self.send_header('Content-Type', 'multipart/x-mixed-replace; boundary=FRAME')
self.end_headers()
try:
while True:
with output.condition:
output.condition.wait()
frame = output.frame
self.wfile.write(b'--FRAME\r\n')
self.send_header('Content-Type', 'image/jpeg')
self.send_header('Content-Length', len(frame))
self.end_headers()
self.wfile.write(frame)
self.wfile.write(b'\r\n')
except Exception as e:
logging.warning(
'Removed streaming client %s: %s',
self.client_address, str(e))
else:
self.send_error(404)
self.end_headers()
class StreamingServer(socketserver.ThreadingMixIn, server.HTTPServer):
allow_reuse_address = True
daemon_threads = True
output = StreamingOutput() # 전역변수로 사용
camera_thread.py
output
객체로 보낸다. import threading
from picamera2 import Picamera2
from picamera2.encoders import JpegEncoder
from picamera2.outputs import FileOutput
import libcamera
import streaming
class CameraThread(threading.Thread):
def __init__(self):
super().__init__()
self.picam2 = Picamera2()
self.picam2.configure(self.picam2.create_video_configuration(main={"size": (640, 480)}))
self.picam2.configure(self.picam2.create_video_configuration(transform=libcamera.Transform(hflip=1, vflip=1)))
self.picam2.start_recording(JpegEncoder(), FileOutput(streaming.output))
def run(self):
try:
address = ('', 8000)
server = streaming.StreamingServer(address, streaming.StreamingHandler)
server.serve_forever()
finally:
self.picam2.stop_recording()