Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # OpenCV Line following rover basics Py2Cv3
- # Will be used and demonstrated with this Vehikel soon: https://www.youtube.com/watch?v=7wFg_FFjx6Y
- import numpy as np
- import cv2
- import time
- video_capture = cv2.VideoCapture(0)
- video_capture.set(3, 640)
- video_capture.set(4, 480)
- # ---- Function definition for converting scales ------
- def remap(unscaled, to_min, to_max, from_min, from_max):
- return (to_max-to_min)*(unscaled-from_min)/(from_max-from_min)+to_min
- # ---- Main loop ----
- while(True):
- # Capture from camera
- ret, frame = video_capture.read()
- # Crop, select part of image to work with
- crop_img = frame[380:480, 0:640]
- # Make the image greyscale
- gray = cv2.cvtColor(crop_img, cv2.COLOR_BGR2GRAY)
- # uncomment next line to view greyscale image
- #cv2.imshow('Gray',gray)
- # Apply a Gaussian blur
- blur = cv2.GaussianBlur(gray,(5,5),0)
- # uncomment next line to view Blurred image
- #cv2.imshow('Blur',blur)
- # Apply Color thresholding
- ret,thresh = cv2.threshold(blur,100,255,cv2.THRESH_BINARY_INV)
- # uncomment next line to view Threshholded image
- #cv2.imshow('Thresh',thresh)
- # Find the contours in the cropped image part
- img, contours, hierarchy = cv2.findContours(thresh.copy(), 1, cv2.CHAIN_APPROX_NONE)
- # ---------------- Find the biggest contour = line -----------------
- if len(contours) > 0:
- c = max(contours, key=cv2.contourArea)
- M = cv2.moments(c)
- cx = int(M['m10']/M['m00'])
- cy = int(M['m01']/M['m00'])
- cv2.line(crop_img,(cx,0),(cx,720),(255,255,0),2)
- cv2.line(crop_img,(0,cy),(1280,cy),(0,255,0),2)
- cv2.drawContours(crop_img, contours, -1, (0,255,255), 2)
- # ---- Draw centre boundry lines (Steer straight)
- cv2.line(crop_img,(270,0),(270,480),(0,0,255),2)
- cv2.line(crop_img,(370,0),(370,480),(0,0,255),2)
- # --------- Steer Right Routine ----------
- if cx >= 370:
- RSteer = cx - 370
- SteerRight = remap(RSteer, 0, 45, 1, 270)
- print ("Turn Right: ", SteerRight)
- # --------- On Track Routine ----------
- if cx < 370 and cx > 270:
- print "On Track"
- # --------- Steer Left Routine ----------
- if cx <= 270:
- LSteer = 270 - cx
- SteerLeft = remap(LSteer, 0, 45, 1, 270)
- print ("Turn Left: ", SteerLeft)
- # ------ Show the resulting cropped image
- cv2.imshow('frame',crop_img)
- if cv2.waitKey(1) & 0xFF == ord('q'):
- break
- #https://www.facebook.com/mrlunk
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement