Untitled

mail@pastecode.io avatar
unknown
python
a month ago
2.6 kB
1
Indexable
Never
import cv2
import numpy as np

# Menginisialisasi webcam
cap = cv2.VideoCapture(0)

# Baca frame pertama
ret, frame1 = cap.read()
ret, frame2 = cap.read()

while cap.isOpened():
    # Hitung perbedaan antara dua frame
    diff = cv2.absdiff(frame1, frame2)
    gray = cv2.cvtColor(diff, cv2.COLOR_BGR2GRAY)
    blur = cv2.GaussianBlur(gray, (5,5), 0)
    _, thresh = cv2.threshold(blur, 20, 255, cv2.THRESH_BINARY)
    dilated = cv2.dilate(thresh, None, iterations=3)
    contours, _ = cv2.findContours(dilated, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

    for contour in contours:
        if cv2.contourArea(contour) < 5000:
            continue
        x, y, w, h = cv2.boundingRect(contour)
        cv2.rectangle(frame1, (x, y), (x+w, y+h), (0, 255, 0), 2)

    cv2.imshow("feed", frame1)
    frame1 = frame2
    ret, frame2 = cap.read()

    if cv2.waitKey(10) == 27: # Tekan ESC untuk keluar
        break

cap.release()
cv2.destroyAllWindows()
Integrasi dengan Clarifai API
Untuk menggunakan Clarifai API, Anda harus menginstal paket clarifai terlebih dahulu dan menginisialisasi client-nya.

bash
Copy code
pip install clarifai
python
Copy code
from clarifai.rest import ClarifaiApp
import cv2
import base64

# Menginisialisasi Clarifai API
app = ClarifaiApp(api_key='YOUR_CLARIFAI_API_KEY')
model = app.public_models.general_model

# Fungsi untuk mengirim gambar ke Clarifai API dan mendapatkan hasil analisis
def analyze_frame(image):
    _, img_encoded = cv2.imencode('.jpg', image)
    img_base64 = base64.b64encode(img_encoded).decode('utf-8')
    response = model.predict_by_base64(img_base64)
    return response

# Menginisialisasi webcam
cap = cv2.VideoCapture(0)
ret, frame1 = cap.read()
ret, frame2 = cap.read()

while cap.isOpened():
    diff = cv2.absdiff(frame1, frame2)
    gray = cv2.cvtColor(diff, cv2.COLOR_BGR2GRAY)
    blur = cv2.GaussianBlur(gray, (5,5), 0)
    _, thresh = cv2.threshold(blur, 20, 255, cv2.THRESH_BINARY)
    dilated = cv2.dilate(thresh, None, iterations=3)
    contours, _ = cv2.findContours(dilated, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

    for contour in contours:
        if cv2.contourArea(contour) < 5000:
            continue
        x, y, w, h = cv2.boundingRect(contour)
        cv2.rectangle(frame1, (x, y), (x+w, y+h), (0, 255, 0), 2)
        # Analisis frame jika ada gerakan
        analysis = analyze_frame(frame1[y:y+h, x:x+w])
        print(analysis)

    cv2.imshow("feed", frame1)
    frame1 = frame2
    ret, frame2 = cap.read()

    if cv2.waitKey(10) == 27: # Tekan ESC untuk keluar
        break

cap.release()
cv2.destroyAllWindows()
Leave a Comment