inflearn logo
강의

Khóa học

Chia sẻ kiến thức

[Raspberry Pi] Dự án thực hành thị giác máy tính học sâu về IoT

주차장차량세기 picamera

216

sooyeon9908282434

5 câu hỏi đã được viết

0

안녕하세요 주차장 차량세는거에 picamera를 작동시키고 싶어서 얼굴인식부분에서 파이카메라 불러오는 부분이랑 코드를 합치려고 하는데요 합치다보니 잘 안되가지고 질문 남깁니다

소스코드

import cv2

import numpy as np

import time

min_confidence = 0.5

margin = 30

file_name = "image/parking_03.jpg"

# Load Yolo

net = cv2.dnn.readNet("yolo/yolov3-tiny.weights", "yolo/yolov3-tiny.cfg")

classes = []

with open("yolo/coco.names", "r") as f:

    classes = [line.strip() for line in f.readlines()]

print(classes)

layer_names = net.getLayerNames()

output_layers = [layer_names[i[0] - 1] for i in net.getUnconnectedOutLayers()]

# Loading image

start_time = time.time()

img = cv2.imread(file_name)

height, width, channels = img.shape

# Detecting objects

blob = cv2.dnn.blobFromImage(img, 0.00392, (416, 416), (0, 0, 0), True, crop=False)

net.setInput(blob)

outs = net.forward(output_layers)

# Showing informations on the screen

confidences = []

boxes = []

for out in outs:

    for detection in out:

        scores = detection[5:]

        class_id = np.argmax(scores)

        confidence = scores[class_id]

        # Filter only 'car'

        if class_id == 2 and confidence > min_confidence:

            # Object detected

            center_x = int(detection[0] * width)

            center_y = int(detection[1] * height)

            w = int(detection[2] * width)

            h = int(detection[3] * height)

            # Rectangle coordinates

            x = int(center_x - w / 2)

            y = int(center_y - h / 2)

            boxes.append([x, y, w, h])

            confidences.append(float(confidence))

indexes = cv2.dnn.NMSBoxes(boxes, confidences, min_confidence, 0.4)

font = cv2.FONT_HERSHEY_PLAIN

color = (0, 255, 0)

for i in range(len(boxes)):

    if i in indexes:

        x, y, w, h = boxes[i]

        label = '{:,.2%}'.format(confidences[i])

        print(i, label)

        cv2.rectangle(img, (x, y), (x + w, y + h), color, 2)

        cv2.putText(img, label, (x, y - 10), font, 1, color, 2)

        

text = "Number of Car is : {} ".format(len(indexes))

cv2.putText(img, text, (margin, margin), font, 2, color, 2)

cv2.imshow("Number of Car - "+file_name, img)

end_time = time.time()

process_time = end_time - start_time

print("=== A frame took {:.3f} seconds".format(process_time))

# https://firebase.google.com/docs/admin/setup#prerequisites

# https://firebase.google.com/docs/database/admin/start

import firebase_admin

from firebase_admin import credentials

from firebase_admin import db

from firebase_admin import storage

# Fetch the service account key JSON file contents

cred = credentials.Certificate('streetlamp-2e57a-firebase-adminsdk-gseyz-5b0121b783.json')

# Initialize the app with a service account, granting admin privileges

firebase_admin.initialize_app(cred, {

    'databaseURL': 'https://streetlamp-2e57a-default-rtdb.firebaseio.com/',

    'storageBucket': 'streetlamp-2e57a.appspot.com'

})

bucket = storage.bucket()

blob = bucket.blob(file_name)

#blob.upload_from_filename(

#        file_name,

#        content_type='image/jpg'

#    )

blob.upload_from_filename(file_name)

ref = db.reference('parking')

box_ref = ref.child('west-coast')

box_ref.update({

    'count': len(indexes),

    'time': time.time(),

    'image': blob.public_url

})

cv2.waitKey(0)

cv2.destroyAllWindows()

코드는 이렇게 합쳤는데 오류 코드는 밑과 같습니다.

Traceback (most recent call last):

  File "/home/pi/rbp_dnn/RBP_DL21_YOLO_car.py", line 48, in <module>

    for frame in camera.capture_continuous(rawCapture, format="bgr", use_video_port=True):

  File "/usr/lib/python3/dist-packages/picamera/camera.py", line 1702, in capture_continuous

    if not encoder.wait(self.CAPTURE_TIMEOUT):

  File "/usr/lib/python3/dist-packages/picamera/encoders.py", line 395, in wait

    self.stop()

  File "/usr/lib/python3/dist-packages/picamera/encoders.py", line 419, in stop

    self._close_output()

  File "/usr/lib/python3/dist-packages/picamera/encoders.py", line 349, in _close_output

    mo.close_stream(output, opened)

  File "/usr/lib/python3/dist-packages/picamera/mmalobj.py", line 371, in close_stream

    stream.flush()

  File "/usr/lib/python3/dist-packages/picamera/array.py", line 238, in flush

    self.array = bytes_to_rgb(self.getvalue(), self.size or self.camera.resolution)

  File "/usr/lib/python3/dist-packages/picamera/array.py", line 127, in bytes_to_rgb

    'Incorrect buffer length for resolution %dx%d' % (width, height))

picamera.exc.PiCameraValueError: Incorrect buffer length for resolution 640x480

구글링해봤는데 해결이 안되서 올립니다 ㅜㅜ

딥러닝 iot Raspberry-Pi 컴퓨터-비전 tensorflow keras

Câu trả lời 1

0

nomad

안녕하세요?

강의를 보시면 picamera를 사용하는 에제가 있습니다. 그 내용을 보시고 적용하시기 바랍니다.

감사합니다.

RBP_DL01_Raspberry pi inatall 문서 다운로드위치는?

0

72

1

강의 자료 다운관련 문의 드립니다.

0

129

1

강의자료를 크리애플 홈페이지에서 찾을 수 없네요..

0

374

1

64bit picamera 관련 질문

0

892

1

라즈베리파이 firebase 설치오류

0

537

0

도와주세요

0

341

1

64비트에서는 안되는건가요?

0

308

1

코드 크리애플 홈피에 없는데 어디있나요

0

382

1

답변 부탁드려요.

0

242

1

자료 강의 구매해야하던데, 답변 부탁드려요

0

325

0

현재 인프런에서 강의 듣고 있는데 자료가 없습니다. 자료 공유관련 답변 부탁드립니다.

0

341

2

라즈베리파이 hdmi 케이블

0

465

1

안녕하세요 크리애플 구독관련해서 질문드립니다.

0

213

0

강의 업데이트 부탁드립니다. 텐서플로워 설치가 안됩니다.

2

440

1

pygame 설치 오류

0

449

0

소스코드 다운 받으려면 결제를 해야 하나요?

0

204

1

얼굴 인식 정확도

0

299

1

import dropbox 오류

0

204

1

conda install -c conda-forgo dlib 오류

0

386

1

라즈베리파이에서 RBP_DL21_YOLO_car.py 실행시

0

218

1

강의와 다른 라즈베리파이 홈페이지

0

336

1

ModuleNotFoundError: No module named 'cv2' (해결)

0

6062

2

no module named 'cv2'

0

750

4

import error

0

413

2