简体   繁体   中英

Raspberry Pi + Camera + Stepper Motors + Open CV

I have written a program that basically brings a tray under a camera connected to a Raspberry Pi sequentially using a stepper motor+ a4988 driver. The code brings a tray to a start position, takes a step, takes a photo and repeats this 10 times. The tray is then returned to the start position. What I should get is 10 photos of each section of the tray with whatever is on the tray.

However, what I get out is 7 photos that are exactly the same photo and then 3 that are different and I cant work out why.

I think that the camera is taking the photos at a faster rate than the tray is moving but from the code I cant see why that would be.

Im using openCV to get the photo because I plan to analyse each photo as it comes in.

Thanks!!

Heres my code:

from time import sleep
import RPi.GPIO as GPIO
import cv2

cam = cv2.VideoCapture(0)

DIR = 20   # Direction GPIO Pin
STEP = 21  # Step GPIO Pin
CW = 1     # Clockwise Rotation
CCW = 0    # Counterclockwise Rotation
SPR = 200   # Steps per Revolution (360 / 1.8)

GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.setup(DIR, GPIO.OUT)
GPIO.setup(STEP, GPIO.OUT)
GPIO.output(DIR, CW)

MODE = (14, 15, 18)   # Microstep Resolution GPIO Pins
GPIO.setup(MODE, GPIO.OUT)
RESOLUTION = {'Full': (0, 0, 0),
              'Half': (1, 0, 0),
              '1/4': (0, 1, 0),
              '1/8': (1, 1, 0),
              '1/16': (1, 1, 1),}

GPIO.output(MODE, RESOLUTION['1/16'])
delay2 = 0.0208/32
GPIO.output(DIR, CCW)
for x in range (1500): # Brings Tray to level of first photo
    GPIO.output(STEP, GPIO.HIGH)
    sleep(delay2)
    GPIO.output(STEP, GPIO.LOW)
    sleep(delay2)
sleep(.5)
for a in range (0,9): # Begins 10 photos
    for b in range (250): #Motor steps between photos
        GPIO.output(STEP, GPIO.HIGH)
        sleep(delay2)
        GPIO.output(STEP, GPIO.LOW)
        sleep(delay2)
    sleep(.5)

    ret, frame = cam.read() #Sets up cam for photo
    cv2.imwrite("image"+str(a)+".jpg", frame)  #Write photo to file
    sleep(2)

GPIO.output(DIR, CW)
for x in range(3750): # Pushes Tray out to original starting position
    GPIO.output(STEP, GPIO.HIGH)
    sleep(delay2)
    GPIO.output(STEP, GPIO.LOW)
    sleep(delay2)
sleep(.5)

cam.release()
GPIO.cleanup()

Solved it thanks to Mark and Matt. Thanks for all your help. Was solved by calling the video capture at each motor step and then releasing it each time.

Heres the code:

for a in range(1,10):
cam=cv2.VideoCapture(0)
ret, frame = cam.read()
cv2.imwrite('iamge'+str(a)+"jpg", frame)
cam.release

... etc etc.

So for each step the camera is called and released which seems to solve it

Thanks all

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM