diff --git a/newTests/cVkeepSide.py b/newTests/cVkeepSide.py new file mode 100644 index 0000000..9de935d --- /dev/null +++ b/newTests/cVkeepSide.py @@ -0,0 +1,95 @@ +import cv2 +import numpy as np +import time +cap = cv2.VideoCapture(0) +k = np.ones((3, 3), np.uint8) +t0 = cap.read()[1] +t1 = cap.read()[1] +allcontours = [] +whiteBackground = 0 +autoClear = 0 +width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH )) +height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT )) +thresholdW = int(width / 2) +outputTitleB = "Press ESC to exit. Try a or e or r or (m or l) or (i or k)" +sense = 35 +maxContoursBuffer = 500 +cColor1 = 255 +addToColor = 1 +activeDetect = 1 +holdLeftRight = 0 # 1 = L, 2 = R +frame_rate = 12 +prev = 0 + +while(True): + time_elapsed = time.time() - prev + if time_elapsed > 1./frame_rate: + prev = time.time() + else: + continue + d=cv2.absdiff(t1, t0) + grey = cv2.cvtColor(d, cv2.COLOR_BGR2GRAY) + blur = cv2.GaussianBlur(grey, (3, 3), 0) + ret, th = cv2.threshold( blur,sense, 255, + cv2.THRESH_BINARY) + dilated = cv2.dilate(th, k, iterations=4) + contours, hierarchy = cv2.findContours(dilated, + cv2.RETR_TREE, + cv2.CHAIN_APPROX_NONE) + t2=t0 + if whiteBackground == 1: + cv2.rectangle(t2, (0,0), (width,height), (10,10,10), cv2.FILLED) + + cColor1 = 1 + for x in allcontours: + cColor1 += 0.5 + cv2.drawContours(t2, x, -1, (cColor1,0,0), 3) + + if activeDetect == 1: + if len(allcontours) < maxContoursBuffer: + allcontours += contours[:20] #Add a max. of n data points + if contours: + if thresholdW > allcontours[-1][0][0][0]: + holdLeftRight = 1 + elif width - thresholdW < allcontours[-1][0][0][0]: + holdLeftRight = 2 + allcontours = allcontours[8:] + + if holdLeftRight == 1: + cv2.rectangle(t2, (0,0), (20,height), (0,0,255), cv2.FILLED) + elif holdLeftRight == 2: + cv2.rectangle(t2, (width-20,0), (width,height), (0,0,255), cv2.FILLED) + + cv2.drawContours(t2, contours, -1, (0, 255, 0), 2) + imS = cv2.resize(t2, (1060, 700)) + cv2.imshow(outputTitleB, imS) + #t0=t2 + t0=t1 + t1=cap.read()[1] + cKey = cv2.waitKey(15) + if cKey == 27 : + break + elif cKey == ord('a'): + whiteBackground = 1 - whiteBackground + elif cKey == ord('m'): + sense += 1 + print(sense) + elif cKey == ord('r'): + allcontours = [] + print("reset") + elif cKey == ord('l'): + sense -= 1 + print(sense) + elif cKey == ord('e'): + activeDetect = 1 - activeDetect + print("Is active:" + str(activeDetect)) + elif cKey == ord('i'): + addToColor += 1 + print("Current addColor:" + str(addToColor)) + elif cKey == ord('k'): + addToColor -= 1 + print("Current addColor:" + str(addToColor)) + + +cv2.destroyAllWindows() +cap.release() diff --git a/newTests/marker_test_keep_side.py b/newTests/marker_test_keep_side.py new file mode 100644 index 0000000..9eb88f6 --- /dev/null +++ b/newTests/marker_test_keep_side.py @@ -0,0 +1,165 @@ +#!/usr/bin/env python3 +# license removed for brevity +import rospy +from geometry_msgs.msg import Twist +from imutils.video import VideoStream +import argparse +import imutils +import time +import cv2 as cv +import sys + +# define names of each possible ArUco tag OpenCV supports +ARUCO_DICT = { + "DICT_4X4_50": cv.aruco.DICT_4X4_50, + "DICT_4X4_100": cv.aruco.DICT_4X4_100, + "DICT_4X4_250": cv.aruco.DICT_4X4_250, + "DICT_4X4_1000": cv.aruco.DICT_4X4_1000, + "DICT_5X5_50": cv.aruco.DICT_5X5_50, + "DICT_5X5_100": cv.aruco.DICT_5X5_100, + "DICT_5X5_250": cv.aruco.DICT_5X5_250, + "DICT_5X5_1000": cv.aruco.DICT_5X5_1000, + "DICT_6X6_50": cv.aruco.DICT_6X6_50, + "DICT_6X6_100": cv.aruco.DICT_6X6_100, + "DICT_6X6_250": cv.aruco.DICT_6X6_250, + "DICT_6X6_1000": cv.aruco.DICT_6X6_1000, + "DICT_7X7_50": cv.aruco.DICT_7X7_50, + "DICT_7X7_100": cv.aruco.DICT_7X7_100, + "DICT_7X7_250": cv.aruco.DICT_7X7_250, + "DICT_7X7_1000": cv.aruco.DICT_7X7_1000, + "DICT_ARUCO_ORIGINAL": cv.aruco.DICT_ARUCO_ORIGINAL, + "DICT_APRILTAG_16h5": cv.aruco.DICT_APRILTAG_16h5, + "DICT_APRILTAG_25h9": cv.aruco.DICT_APRILTAG_25h9, + "DICT_APRILTAG_36h10": cv.aruco.DICT_APRILTAG_36h10, + "DICT_APRILTAG_36h11": cv.aruco.DICT_APRILTAG_36h11, +} + + +def talker(): + # construct the argument parser and parse the argument + ap = argparse.ArgumentParser() + ap.add_argument( + "-t", + "--type", + type=str, + default="DICT_ARUCO_ORIGINAL", + help="type of ArCUo tag to detect", + ) + args = vars(ap.parse_args()) + + # verify that the supplied ArUCo tag exists and is supported by OpenCV + if ARUCO_DICT.get(args["type"], None) is None: + print("[INFO] ArUCo tag of '{}' is not supported".format(args["type"])) + sys.exit(0) + + # load the ArUCo dictionary and grab hte ArUCo parameters + print("[INFO] detecting '{}' tags...".format(args["type"])) + arucoDict = cv.aruco.getPredefinedDictionary(ARUCO_DICT[args["type"]]) + arucoParams = cv.aruco.DetectorParameters() + detector = cv.aruco.ArucoDetector(arucoDict, arucoParams) + + # initialize the video stream and allow the camera sensor to warm up + print("[INFO] starting video stream...") + vs = VideoStream(src=0).start() + + pub = rospy.Publisher("turtle1/cmd_vel", Twist, queue_size=10) + rospy.init_node("turtle_control", anonymous=True) + rate = rospy.Rate(10) + t = Twist() + + keepLeftRight = 0 #1 = L, 2 = R + frame = vs.read() + frame = imutils.resize(frame) + (h, w) = frame.shape[:2] + threshold = int(w/2) + while not rospy.is_shutdown(): + # grab the frame from the threaded video and resize it + # to have a maximum width of 1000 pixels + frame = vs.read() + frame = imutils.resize(frame) + # detect ArUCo markers in the input frame + (corners, ids, rejected) = detector.detectMarkers(frame) + + # verify *at least* one ArUCo marker was detected + if len(corners) > 0: + # flatten the ArUCo IDs list + ids = ids.flatten() + if [1] in ids: + t.angular.z = 0.1 + t.linear.x = 0.5 + pub.publish(t) + # loop over the detected ArUCo corners + for markerCorner, markerID in zip(corners, ids): + # extract the marker corners (Which are always returned in top-left, top-right, bottom-right, and bottom-left order) + corners = markerCorner.reshape((4, 2)) + (topLeft, topRight, bottomRight, bottomLeft) = corners + # convert each of the (x,y)-coordinates pairs to integers + topRight = (int(topRight[0]), int(topRight[1])) + bottomRight = (int(bottomRight[0]), int(bottomRight[1])) + bottomLeft = (int(bottomLeft[0]), int(bottomLeft[1])) + topLeft = (int(topLeft[0]), int(topLeft[1])) + + # draw the bounding box of the ArUCo detection + cv.line(frame, topLeft, topRight, (0, 255, 0), 2) + cv.line(frame, topRight, bottomRight, (0, 255, 0), 2) + cv.line(frame, bottomRight, bottomLeft, (0, 255, 0), 2) + cv.line(frame, bottomLeft, topLeft, (0, 255, 0), 2) + + # compute and draw the center (x,y)-coordinates of the ArUCo marker + cX = int((topLeft[0] + bottomRight[0]) / 2.0) + cY = int((topLeft[1] + bottomRight[1]) / 2.0) + cv.circle(frame, (cX, cY), 4, (0, 0, 255), -1) + + # draw the ArUCo marker ID on the frame + cv.putText( + frame, + str(markerID), + (topLeft[0], topLeft[1] - 15), + cv.FONT_HERSHEY_SIMPLEX, + 0.5, + (0, 255, 0), + 2, + ) + if threshold > cX: + keepLeftRight = 1 + elif w - threshold < cX: + keepLeftRight = 2 + else: + pass + #No maker detected should turn now! + if keepLeftRight == 1: + cv.rectangle(frame, (0,0), (20,h), (0,0,255), cv.FILLED) + elif keepLeftRight == 2: + cv.rectangle(frame, (w-20,0), (w,h), (0,0,255), cv.FILLED) + + + idString = "IDs:" + str(ids) + cv.putText( + frame, + idString, + (50, 50), + cv.FONT_HERSHEY_SIMPLEX, + 1, + (40, 10, 100), + 3, + cv.LINE_AA, + ) + rate.sleep() + + # show the output frame + cv.imshow("Frame", frame) + key = cv.waitKey(1) & 0xFF + + # if the 'q' key was pressed, break from the loop + if key == ord("q"): + break + # do a bit of cleanup + cv.destroyAllWindows() + vs.stop() + + +if __name__ == "__main__": + try: + talker() + except rospy.ROSInterruptException: + pass