728x90
반응형
GStreamer, OpenCV, ROS/ROS2, DeepStream, YOLO의 언어 지원
GStreamer:
- 언어 지원: GStreamer는 주로 C 언어로 작성되어 있으며, Python, C++, Java, Ruby, Perl 등 다양한 언어 바인딩을 제공합니다.
- 대중적 언어: 가장 대중적으로 사용하는 언어는 C와 Python입니다. C는 성능 최적화가 필요할 때, Python은 빠른 프로토타이핑과 높은 생산성을 위해 주로 사용됩니다.
OpenCV (Open Source Computer Vision Library):
- 언어 지원: OpenCV는 C++로 작성되어 있으며, Python, Java, MATLAB, C 등 다양한 언어 바인딩을 제공합니다.
- 대중적 언어: 가장 대중적으로 사용하는 언어는 Python과 C++입니다. Python은 간결하고 사용하기 쉬워 많은 개발자들이 선호하며, C++는 성능이 중요한 애플리케이션에서 주로 사용됩니다.
ROS/ROS2 (Robot Operating System):
- 언어 지원: ROS는 주로 C++와 Python을 지원합니다. ROS2는 C++와 Python뿐만 아니라 더 많은 언어를 지원할 계획이 있습니다.
- 대중적 언어: 가장 대중적으로 사용하는 언어는 C++와 Python입니다. C++는 실시간 성능과 시스템 통합에 유리하고, Python은 스크립팅과 빠른 개발에 유리합니다.
DeepStream:
- 언어 지원: DeepStream은 주로 C와 Python을 지원합니다. NVIDIA는 주로 C/C++와 Python 예제를 제공합니다.
- 대중적 언어: 가장 대중적으로 사용하는 언어는 C/C++와 Python입니다. Python은 빠른 프로토타이핑에 유리하고, C/C++는 성능 최적화에 유리합니다.
YOLO (You Only Look Once):
- 언어 지원: YOLO는 주로 C와 Python을 지원합니다. 원래는 C로 작성되었지만, 많은 Python 바인딩이 존재합니다.
- 대중적 언어: 가장 대중적으로 사용하는 언어는 Python입니다. Python은 딥러닝 프레임워크(TensorFlow, PyTorch)와의 통합이 쉽기 때문입니다.
드론 제어 예제 코드
다음은 OpenCV, ROS2, YOLO 라이브러리를 사용하여 드론을 제어하고, 영상을 촬영하여 저장하며, 사람 객체를 인식해 인식된 부분을 캡처하여 저장하는 예제 코드입니다. 이 예제는 Python을 기반으로 작성되었습니다.
1. 환경 설정
- Python 3
- ROS2
- OpenCV
- YOLO (YOLOv3 모델)
- 드론 제어 라이브러리 (예: DJITelloPy)
2. 예제 코드
import cv2
import numpy as np
import rospy
from sensor_msgs.msg import Image
from cv_bridge import CvBridge
from djitellopy import Tello
# YOLO 모델 설정
YOLO_WEIGHTS = "yolov3.weights"
YOLO_CONFIG = "yolov3.cfg"
YOLO_CLASSES = "coco.names"
# Load YOLO
net = cv2.dnn.readNet(YOLO_WEIGHTS, YOLO_CONFIG)
with open(YOLO_CLASSES, "r") as f:
classes = [line.strip() for line in f.readlines()]
layer_names = net.getLayerNames()
output_layers = [layer_names[i[0] - 1] for i in net.getUnconnectedOutLayers()]
# Initialize ROS node
rospy.init_node('drone_controller', anonymous=True)
bridge = CvBridge()
# Initialize Tello drone
drone = Tello()
drone.connect()
drone.streamon()
def capture_and_detect():
frame_read = drone.get_frame_read()
frame = frame_read.frame
height, width, channels = frame.shape
blob = cv2.dnn.blobFromImage(frame, 0.00392, (416, 416), (0, 0, 0), True, crop=False)
net.setInput(blob)
outs = net.forward(output_layers)
class_ids = []
confidences = []
boxes = []
for out in outs:
for detection in out:
scores = detection[5:]
class_id = np.argmax(scores)
confidence = scores[class_id]
if confidence > 0.5 and classes[class_id] == "person":
center_x = int(detection[0] * width)
center_y = int(detection[1] * height)
w = int(detection[2] * width)
h = int(detection[3] * height)
x = int(center_x - w / 2)
y = int(center_y - h / 2)
boxes.append([x, y, w, h])
confidences.append(float(confidence))
class_ids.append(class_id)
indexes = cv2.dnn.NMSBoxes(boxes, confidences, 0.5, 0.4)
for i in range(len(boxes)):
if i in indexes:
x, y, w, h = boxes[i]
label = str(classes[class_ids[i]])
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
cv2.putText(frame, label, (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
person_img = frame[y:y+h, x:x+w]
cv2.imwrite(f"captured_person_{i}.jpg", person_img)
cv2.imshow("Frame", frame)
cv2.waitKey(1)
img_msg = bridge.cv2_to_imgmsg(frame, "bgr8")
image_pub.publish(img_msg)
image_pub = rospy.Publisher('/drone/image_raw', Image, queue_size=10)
if __name__ == "__main__":
try:
while not rospy.is_shutdown():
capture_and_detect()
except rospy.ROSInterruptException:
pass
finally:
drone.streamoff()
cv2.destroyAllWindows()
설명
- YOLO 모델 설정: YOLOv3 모델을 사용하여 객체 인식을 수행합니다.
- ROS 노드 초기화: ROS 노드를 초기화하고 이미지 메시지 퍼블리셔를 설정합니다.
- Tello 드론 초기화: Tello 드론을 초기화하고 비디오 스트림을 시작합니다.
- 객체 인식 및 이미지 캡처: 드론에서 프레임을 캡처하고 YOLO를 사용하여 사람 객체를 인식한 후, 인식된 부분을 별도로 캡처하여 저장합니다. 또한, 결과 이미지를 ROS 주제로 퍼블리싱합니다.
이 예제는 드론을 제어하고, 실시간으로 영상을 캡처하며, YOLO를 사용하여 사람 객체를 인식하는 과정을 보여줍니다. 추가로 궁금한 점이 있으면 언제든지 말씀해 주세요!
'Coding 공부 > Python' 카테고리의 다른 글
[Python] 드론을 활용한 실시간 객체 인식 및 이미지 캡처 예제코드 (5) | 2024.07.21 |
---|---|
[Python] 드론제어 예제코드(상세) Python3, ROS2, OpenCV, YOLO, DJITelloPy (2) | 2024.07.20 |
[Python] ImgBB : 이미지 호스팅 API (0) | 2024.06.26 |
[Python] 이미지 해상도 낮추기 Pillow 라이브러 (0) | 2024.06.22 |
[Python_Summary] 클래스 (0) | 2024.02.01 |
댓글