Python Forum

Full Version: Error in Raspberry Pi
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Merry Christmas and good evening to everyone. I have a hand tracking code.I wrote the code by combining two different codes with chat gpt. I try to fix errors but I cant fix this error. This line written by ai.

I got "syntax error: invalid syntax" for this line:
'mpDraw.draw_landmarks(img, handLms, mpHands.HAND_CONNECTIONS)'

This is my whole code:
import cv2
import time
import mediapipe as mp
import numpy as np
import math
import board
import busio
import adafruit_mcp4725
import RPi.GPIO as GPIO

# Initialize I2C DAC for frequency control (MCP4725)
i2c = busio.I2C(board.SCL, board.SDA)
dac = adafruit_mcp4725.MCP4725(i2c)

# Initialize GPIO pins for amplitude control (digipot)
CS = 17   # BCM GPIO17
INC = 27  # BCM GPIO27
UD = 22   # BCM GPIO22

GPIO.setmode(GPIO.BCM)
GPIO.setup(CS, GPIO.OUT)
GPIO.setup(INC, GPIO.OUT)
GPIO.setup(UD, GPIO.OUT)

GPIO.output(CS, GPIO.HIGH)
GPIO.output(INC, GPIO.HIGH)
GPIO.output(UD, GPIO.LOW)

# Camera and hand tracking setup
cap = cv2.VideoCapture(0)  # Removed cv2.CAP_DSHOW for Raspberry Pi compatibility

min_freq = 100
max_freq = 1000
y_min = 0
y_max = 600

mpHands = mp.solutions.hands
hands = mpHands.Hands(min_detection_confidence=0.8,
                      min_tracking_confidence=0.75,
                      max_num_hands=2)
mpDraw = mp.solutions.drawing_utils

pTime = 0
cTime = 0

# Initialize amplitude and frequency with default values
amplitude = 100
frequency = 100

def set_digipot_level(new_amplitude, current_position):
    """Control amplifier level via digipot"""
    # Convert amplitude (100 to 32767) to digipot steps (0 to 99)
    new_position = int((new_amplitude - 100) * (99 / (32767 - 100)))
    new_position = max(0, min(99, new_position))

    steps = abs(new_position - current_position)
    direction = (new_position > current_position)
    
    GPIO.output(CS, GPIO.LOW)
    GPIO.output(UD, GPIO.HIGH if direction else GPIO.LOW)
    
    for _ in range(steps):
        GPIO.output(INC, GPIO.LOW)
        time.sleep(0.001)
        GPIO.output(INC, GPIO.HIGH)
        time.sleep(0.001)
        
    GPIO.output(CS, GPIO.HIGH)
    return new_position

def get_label(index, results):
    output = None
    if results.multi_handedness:
        for idx, classification in enumerate(results.multi_handedness):
            if classification.classification[0].index == index:
                output = classification.classification[0].label
    return output

try:
    current_digipot_position = 0  # Track the current position of the digipot
    
    while True:
        success, img = cap.read()
        if not success:
            print("Failed to capture image from camera.")
            break
        img = cv2.flip(img, 1)
        imgRGB = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

        cTime = time.time()
        fps = 1 / (cTime - pTime)
        pTime = cTime

        results = hands.process(imgRGB)
        if results.multi_hand_landmarks:
            for hand_index, handLms in enumerate(results.multi_hand_landmarks):
                handType = get_label(hand_index, results)
                for lm_id, lm in enumerate(handLms.landmark):
                    h, w, c = img.shape

                    cy = abs(cy - 640)
                    cy -= y_min

                    if lm_id == 8 and handType:
                        if handType == 'Left':
                            # Control amplitude via digipot
                            if cy < 187:
                                amplitude = 100 
                            elif cy < 612:
                                amplitude = int(100 + (32667 - 100) * ((cy - 187) / (612 - 187)))
                            else:
                                amplitude = 32767
                            
                            current_digipot_position = set_digipot_level(amplitude, current_digipot_position)
                            
                        elif handType == 'Right':
                            # Control frequency via DAC
                            if cy < 187:
                                frequency = 100
                            elif cy < 612:
                                frequency = int(100 + (1000 - 100) * ((cy - 187) / (612 - 187)))
                            else:
                                frequency = 1000
                            
                            # Convert frequency to DAC value (0-65535 range for MCP4725)
                            dac_value = int((frequency - min_freq) * (65535 / (max_freq - min_freq)))
                            dac_value = max(0, min(65535, dac_value))
                            dac.value = dac_value

                mpDraw.draw_landmarks(img, handLms, mpHands.HAND_CONNECTIONS)

        cv2.putText(img, "FPS:" + str(int(fps)), (10, 75), cv2.FONT_HERSHEY_PLAIN, 3, (255, 0, 0), 5)
        cv2.imshow("img", img)

        if cv2.waitKey(1) & 0xFF == ord('q'):
            break

finally:
    cap.release()
    cv2.destroyAllWindows()
    GPIO.cleanup()
if AI made an error then AI should be the one to research why it made an error.