Comment suivre votre Robot avec OpenCV (11 / 28 étapes)

Etape 11 : Prenez garde vous qui Entrez ici

OK.  Voici tout le code Python en une seule fois. N’ayez pas peur si cela semble confus.  Je ressens la même chose.  En effet, certaines d'entre elles je ne comprends toujours pas.  (Hey, honnêteté un est une anomalie rare je semble posséder.)  Encore une fois, ne vous inquiétez pas, nous allons marcher à travers elle une section à la fois, vous et moi, mon pote.  Jusqu'à la fin.

Sur le revers, si vous êtes un gourou Python ou yanno, juste une impertinente-Jeans/Pantalons : n’hésitez pas à ajouter des corrections et des commentaires sur cette page.  J’aimerais faire ce code se développer par le biais de critique.  Ne sais pas, je vous garantis ce qui suit : fautes de frappe, des problèmes de grammaire, illogique de codage, des artefacts de débogage et similaires.  Mais ne vous inquiétez pas, je suis épaisse peau et généralement porter mes culottes de grand garçon.

Je devrais dire, le code de base pour la couleur de suivi a été écrit par Abid Rahman dans une réponse sur le Débordement de pile.

En outre, j’ai inclus le code en pièce jointe, c’est au fond.  Sud de jeux vidéo.

 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 #Written by the pathos filled hack: C. Thomas Brittainimportcv2importnumpyasnpimportserialfromtimeimport sleep importthreadingimportmathfrommathimport atan2, degrees, pi importrandom#Open COM port to tether the bot. ser = serial.Serial('COM34', 9600) #For getting information from the Arduino (tx was taken by Target X :P)global rx rx =" "#For sending information to the Arduinoglobal tranx tranx =0#For converting the compass heading into an integerglobal intRx intRx =0#I've not used this yet, but I plan on scaling motor duration based#how far away from the targetglobal motorDuration motorDuration =0#A flag variable for threading my motor timer.global motorBusy motorBusy ="No"#Holds the frame indexglobal iFrame iFrame =0defOpenCV(): #Create video capture cap = cv2.VideoCapture(0) #Globalizing variablesglobal cxAvg #<----I can't remember why...global cxFound global iFrame global intRx global rx global tranx #Flag for getting a new target. newTarget ="Yes"#Dot counter. He's a hungry hippo... dots =0#This holds the bot's centroid X & Y average cxAvg =0 cyAvg =0#Stores old position for movement assessment. xOld =0 yOld =0#Clearing the serial send string. printRx =" "while(1): #"printRx" is separate in case I want to #parse out other sensor data from the bot printRx =str(intRx) #Bot heading, unmodified headingDeg = printRx #Making it a number so we can play with it. intHeadingDeg =int(headingDeg) headingDeg =str(intHeadingDeg) #Strings to hold the "Target Lock" status. stringXOk =" " stringYOk =" "#Incrementing frame index iFrame = iFrame +1#Read the frames _,frame = cap.read() #Smooth it frame = cv2.blur(frame,(3,3)) #Convert to hsv and find range of colors hsv = cv2.cvtColor(frame,cv2.COLOR_BGR2HSV) thresh = cv2.inRange(hsv,np.array((0, 80, 80)), / np.array((20, 255, 255))) thresh2 = thresh.copy() #Find contours in the threshold image contours,hierarchy = cv2.findContours (thresh,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE) #Finding contour with maximum area and store it as best_cnt max_area =0for cnt in contours: area = cv2.contourArea(cnt) if area > max_area: max_area = area best_cnt = cnt #Finding centroids of best_cnt and draw a circle there M = cv2.moments(best_cnt) cx,cy =int(M['m10']/M['m00']), int(M['m01']/M['m00']) cv2.circle(frame,(cx,cy),10,255,-1) #After 150 frames, it compares the bot's X and X average,#if they are the same + or - 5, it assumes the bot is being tracked.if iFrame >=150: if cxAvg < (cx +5) and cxAvg > (cx -5): xOld == cxAvg stringXOk ="X Lock"if cyAvg < (cy +5) and cyAvg > (cy -5): yOld == cyAvg stringYOk ="Y Lock"#This is finding the average of the X cordinate. Used for establishing#a visual link with the robot.#X cxAvg = cxAvg + cx cxAvg = cxAvg /2#Y cyAvg = cyAvg + cy cyAvg = cyAvg /2#//Finding the Target Angle/////////////////////////////////////#Target cordinates.#Randomizing target.if newTarget =="Yes": tX = random.randrange(200, 400, 1) tY = random.randrange(150, 350, 1) newTarget ="No"if iFrame >=170: if tX > cxAvg -45and tX < cxAvg +45: print"Made it through the X"if tY > cyAvg -45and tY < cyAvg +45: print"Made it through the Y" newTarget ="Yes" dots=dots+1#Slope dx = cxAvg - tX dy = cyAvg - tY #Quad I -- Goodif tX >= cxAvg and tY <= cyAvg: rads = atan2(dy,dx) degs = degrees(rads) degs = degs -90#Quad II -- Goodelif tX >= cxAvg and tY >= cyAvg: rads = atan2(dx,dy) degs = degrees(rads) degs = (degs *-1) #Quad IIIelif tX <= cxAvg and tY >= cyAvg: rads = atan2(dx,-dy) degs = degrees(rads) degs = degs +180#degs = 3elif tX <= cxAvg and tY <= cyAvg: rads = atan2(dx,-dy) degs = degrees(rads) +180#degs = 4#Convert float to int targetDegs =int(math.floor(degs)) #Variable to print the degrees offset from target angle. strTargetDegs =" "#Put the target angle into a string to printed. strTargetDegs =str(math.floor(degs)) #///End Finding Target Angle////////////////////////////////////#//// Move Bot //////////////////////////////////////#Don't start moving until things are ready.if iFrame >=160: #This compares the bot's heading with the target angle. It must#be +-30 for the bot to move forward, otherwise it will turn.if intHeadingDeg <= (targetDegs +30) and intHeadingDeg >+ (targetDegs -30): tranx =3 motorDuration =10#I'll use later#Forwardelse: if intHeadingDeg < targetDegs: if1< (targetDegs - intHeadingDeg): #abs(intHeadingDeg - targetDegs) >= 180: tranx =2 motorDuration =10print (intHeadingDeg - targetDegs) print"Right 1"elif1> (targetDegs - intHeadingDeg): #abs(intHeadingDeg - targetDegs) < 180: tranx =4 motorDuration =10print (intHeadingDeg - targetDegs) print"Left 1"elif intHeadingDeg >= targetDegs: if1< (targetDegs - intHeadingDeg): #abs(intHeadingDeg - targetDegs) <= 180: tranx =2 motorDuration =10print (intHeadingDeg - targetDegs) print"Right 2"elif1> (targetDegs - intHeadingDeg): #abs(intHeadingDeg - targetDegs) > 180: tranx =4 motorDuration =10print (intHeadingDeg - targetDegs) print"Left 2"#//// End Move Bot //////////////////////////////////#////////CV Dawing//////////////////////////////#Target circle cv2.circle(frame, (tX, tY), 10, (0, 0, 255), thickness=-1) #ser.write(botXY)#Background for text. cv2.rectangle(frame, (18,2), (170,160), (255,255,255), -1) #Target angle. cv2.line(frame, (tX,tY), (cxAvg,cyAvg),(0,255,0), 1) #Bot's X and Y is written to image cv2.putText(frame,str(cx)+" cx, "+str(cy)+" cy",(20,20),cv2.FONT_HERSHEY_COMPLEX_SMALL,.7,(0,0,0)) #Bot's X and Y averages are written to image cv2.putText(frame,str(cxAvg)+" cxA, "+str(cyAvg)+" cyA",(20,40),cv2.FONT_HERSHEY_COMPLEX_SMALL,.7,(0,0,0)) #"Ok" is written to the screen if the X&Y are close to X&Y Avg for several iterations. cv2.putText(frame,stringXOk,(20,60),cv2.FONT_HERSHEY_COMPLEX_SMALL,.7,(0,0,0)) cv2.putText(frame,stringYOk,(20,80),cv2.FONT_HERSHEY_COMPLEX_SMALL,.7,(0,0,0)) #Print the compass to the frame. cv2.putText(frame,"Bot: "+headingDeg+" Deg",(20,100),cv2.FONT_HERSHEY_COMPLEX_SMALL,.7,(0,0,0)) cv2.putText(frame,"Target: "+strTargetDegs+" Deg",(20,120),cv2.FONT_HERSHEY_COMPLEX_SMALL,.7,(0,0,0)) #Dots eaten. cv2.putText(frame,"Dots Ate: "+str(dots),(20,140),cv2.FONT_HERSHEY_COMPLEX_SMALL,.7,(0,0,0)) #After the frame has been modified to hell, show it. cv2.imshow('frame',frame) #Color image cv2.imshow('thresh',thresh2) #Black-n-White Threshold image#/// End CV Draw //////////////////////////////////////if cv2.waitKey(33)==27: # Clean up everything before leaving cv2.destroyAllWindows() cap.release() #Tell the robot to stop before quit. ser.write("5") ser.close() # Closes the serial connection.breakdefrxtx(): # Below 32 everything in ASCII is gibberish counter =32#So the data can be passed to the OpenCV thread.global rx global intRx global tranx global motorDuration global motorBusy while(True): counter +=1# Read the newest output from the Arduino rx = ser.readline() #This is for threading out the motor timer. Allowing for control#over the motor burst duration.if motorBusy =="No": ser.write(tranx) ser.flushOutput() #Clear the buffer? motorBusy ="Yes"#Delay one tenth of a second sleep(.1) #This is supposed to take only the first three digits. rx = rx[:3] #This removes any EOL characters rx = rx.strip() #If the number is less than 3 digits, then it will be included#we get rid of it so we can have a clean str to int conversion. rx = rx.replace(".", "") #We don't like 0. So, this does away with it. try: intRx =int(rx) exceptValueError: intRx =0#Reset counter if over 255.if counter ==255: counter =32defmotorTimer(): global motorDuration global motorBusy while(1): if motorBusy =="Yes": sleep(.2) #Sets the motor burst duration. ser.write("5") sleep(.3) #Sets time inbetween motor bursts. motorBusy ="No"#Threads OpenCV stuff. OpenCV = threading.Thread(target=OpenCV) OpenCV.start() #Threads the serial functions. rxtx = threading.Thread(target=rxtx) rxtx.start() #Threads the motor functions. motorTimer = threading.Thread(target=motorTimer) motorTimer.start() 274 275 1 2 3 4 5 6 7 8 9 10 284 #Written by the pathos filled hack: C. Thomas Brittainimportcv2importnumpyasnpimportserialfromtimeimport sleep importthreadingimportmathfrommathimport atan2, degrees, pi importrandom 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 121314151617181920212223242526272829303132333435363738 344 #Open COM port to tether the bot. ser = serial.Serial('COM34', 9600) #For getting information from the Arduino (tx was taken by Target X :P)global rx rx =" "#For sending information to the Arduinoglobal tranx tranx =0#For converting the compass heading into an integerglobal intRx intRx =0#I've not used this yet, but I plan on scaling motor duration based#how far away from the targetglobal motorDuration motorDuration =0#A flag variable for threading my motor timer.global motorBusy motorBusy ="No"#Holds the frame indexglobal iFrame iFrame =0 
 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 

Articles Liés

Comment suivre votre Mac perdu ou volé

Comment suivre votre Mac perdu ou volé

Si vous avez pensé à permettre de trouver mon Mac, vous pouvez suivre votre Mac, le verrouiller à distance et même envoyer des messages à l'écran de votre Mac. En outre, il y a beaucoup plus de moyens pour suivre sa position et exposer le voleur. Cel
Renforcer votre robot avec sugru

Renforcer votre robot avec sugru

Dans notre hackerspace www.MADspace.nl nous devons construire un robot qui a gagné un prix (voir url : http://hackaday.io/project/740-mars). Mais malheureusement, le matériau est faible et peut casser lorsque le robot de conduite trop fort contre le
Ordinateur, donnez-moi le café ! (Comment construire un Robot avec Interface vocale)

Ordinateur, donnez-moi le café ! (Comment construire un Robot avec Interface vocale)

Me souviens comment nous, humains, interagir avec des ordinateurs dans les films de science-fiction ? Ordinateur faire cela, arrêt de l'ordinateur. Pourquoi nous avons toujours ne vois pas tous cette awesomeness d'interface voix dans nos maisons ? Po
Comment nettoyer votre visage avec Rondoudou

Comment nettoyer votre visage avec Rondoudou

un moyen simple pour nettoyer votre visagevous aurez besoinsavon (bonne odeur)Water(duh)lotion (crème hydratante)chiffon (propre)Étape 1: se laver le visage rincer votre visage avec de l'eau pour enlever la saletéÉtape 2: ajouter le savon obtenir env
Comment construire votre Robot vibrant modulaire

Comment construire votre Robot vibrant modulaire

Electronique + LEGO + sugru=Robot vibrant modulaire !http://youtu.be/ELB-XPDBOFIMotivationDepuis quelques années j'ai joué avec le merveilleux HEXBUG, mais j'ai commencé à obtenir frustré par la-Forme et taille : que je n'ai pas pu changer.-Puissance
Comment emballer votre briquet avec Paracord

Comment emballer votre briquet avec Paracord

ce Instructable vous montrera comment encapsuler un briquet (ou autre objet) en paracorde.J'ai récemment acheté quelques paracord après avoir parcouru instructables et a décidé de faire mes propres ' IbleÉtape 1: Ce que vous aurez besoin Vous aurez b
Suivre votre voiture avec un Lojack axée sur l’Arduino

Suivre votre voiture avec un Lojack axée sur l’Arduino

Vol de voiture est un frein réel ! Augmentez vos chances de récupérer votre voiture en installant ce tracker simple axée sur l'Arduino dans votre voiture.Ce projet est assez simple et serait un bon projet pour un nouveau programmeur Arduino vous cher
Comment suivre votre TIGERweb Mail vers votre compte de messagerie

Comment suivre votre TIGERweb Mail vers votre compte de messagerie

avouons-le, TIGERweb mail est une douleur pour vérifier. Microsoft Outlook Web Access est lente, glitch et généralement désagréable à utiliser.C'est là qu'intervient ce tutoriel. Une fois que vous avez fait ici, vous nous l'espérons sera en mesure de
Comment meubler votre appartement avec outils CNC : partie 1 - tabourets empilables de Aalto

Comment meubler votre appartement avec outils CNC : partie 1 - tabourets empilables de Aalto

J'ai récemment déménagé à un nouvel appartement qui manque cruellement ameublement. Au lieu d'aller sur une séance de magasinage chez IKEA, j'utilise les outils CNC à Autodesk Pier 9 pour meubler mon nouvel appartement. Je n'ai pas toute formation en
Comment utiliser votre MotorShield avec REDUCTEUR

Comment utiliser votre MotorShield avec REDUCTEUR

Je voulais aider à donner la Communauté une plus simple à comprendre le guide d'utilisation de moteurs à courant continu avec le Motorshield qui peut être attachée à votre Arduino.Merci de saisir votre Arduino et MotorShield et j'espère que nous pour
Comment nettoyer votre Mac avec MacKeeper

Comment nettoyer votre Mac avec MacKeeper

avec une utilisation fréquente, disque dur de votre Mac finit par parsemée de données inutiles, et cela affecte les performances de votre Mac. Il existe plusieurs façons de nettoyer votre disque dur, et l'un d'eux consiste à installer et utiliser Mac
ZAPpelin, ou comment former votre dirigeable avec une télécommande Arduino et IR

ZAPpelin, ou comment former votre dirigeable avec une télécommande Arduino et IR

est-il battant seal ? Un battement alien ?Non, c'est un ZAPpelin, un Arduino contrôlée dirigeable intérieure, installation d'apprendre dans les signaux d'une télécommande IR à commande.Ce projet est venu à la vie à la troisième to17th Arduino Jam Feb
Comment exercer votre cheval avec gestion du temps

Comment exercer votre cheval avec gestion du temps

sur un temps crunch mais qui ont du bétail qui a besoin d'exercice ? J'espère que cette aide !Étape 1: planificateur Vérifiez votre calendrier, planificateur ou par téléphone pour les dates ou les réunions à venir. Décider si votre avoir assez de tem
Comment organiser votre calendrier avec des bouchons !

Comment organiser votre calendrier avec des bouchons !

You recycle the bottle, so you might as well recycle the caps too!Il existe des tonnes de façons du re-use/upcycle bouchons et cette volonté instructable vous montrent comment transformer des bouchons en aimants organisationnelles !Vous aurez besoin