Python Script running on the laptop mounted on the turtlebot. started by 'python tutel.py /cmd_vel_mux/input/navi /camera/color/image_raw /camera/color/image_raw <verbose>'
This commit is contained in:
2024-03-13 20:34:04 +01:00
parent 7c117b3a3a
commit ec56aa514f
+498
View File
@@ -0,0 +1,498 @@
#!/usr/bin/env python
from __future__ import print_function
import roslib
import sys
import rospy
import cv2
import time
import numpy as np
import serial
import subprocess
import math
from std_msgs.msg import String
from sensor_msgs.msg import Image
from cv_bridge import CvBridge, CvBridgeError
from geometry_msgs.msg import Twist
TARGET = -1
DEPTH_CAMERA_MIN_THRESHOLD = 530
DEPTH_CAMERA_MAX_THRESHOLD = 1000
POSITIONS = ["left", "right", "middle"]
DEVICE = '/dev/ttyACM'
BAUD = 115200
#marker ids found in the room: 0, 63, 1024
WHITELIST_OBJECT = [1, 6, 123]
WHITELIST_PLACE = [497, 666, 234]
SEARCH = ["no", "object", "place"]
HEIGHT_CAMERA = 310
ARM_LENGTH = 375 #not the real arm length, its the max length from camera to object where our arm can reach the object
CAMERA_TO_ARM = 125
class tutel():
def __init__(self, tutel_topic : str, astra_rgb_topic : str, astra_depth_topic : str, verbose : str = "no", velocity_factor : float = 1.0):
#needed variables, velocity factor is a multiplier for the bot, might be changed later
#target_id used to remember the last id the tutel found, set to -1 at the beginning
self.vel_fac = velocity_factor
self.verbose = verbose
self.target_id = TARGET
self.last_id = TARGET
#auruco init, best dictionary we found atm
self.arucoDict = cv2.aruco.getPredefinedDictionary(cv2.aruco.DICT_ARUCO_ORIGINAL)
self.arucoParams = cv2.aruco.DetectorParameters_create()
#minimal/maximal depth we recognize, still testing for values!
self.max_threshold = DEPTH_CAMERA_MAX_THRESHOLD
self.min_threshold = DEPTH_CAMERA_MIN_THRESHOLD
#Serial Pipeline init
#self.com = self.init_serial()
self.com=3
self.device = DEVICE+str(self.com)
self.baud = BAUD
self.board = serial.Serial(self.device, self.baud, timeout = 1)
time.sleep(5)
self.board.write(bytes("0 0 0", "utf-8"))
while self.board.in_waiting < 3:
self.routine = True
self.board.reset_input_buffer()
self.board.write(bytes("1 1 1", "utf-8"))
while self.board.in_waiting < 3:
self.routine = True
self.board.reset_input_buffer()
#answer =''
#self.board.write(bytes("0","utf-8"))
#while answer != b'1':
#answer = self.board.readline()
#print(answer)
#Tutel_control
self.pub = rospy.Publisher(tutel_topic, Twist, queue_size = 1)
self.wait_publishers(astra_rgb_topic, astra_depth_topic)
self.t = Twist()
self.fresh_start = True
#cv related
#rgb related
self.position = POSITIONS[-1]
self.lastConernerTime = time.time()
self.rgb_bridge = CvBridge()
self.search = SEARCH[1]
self.search_time = time.time()
#depth related
self.depth_bridge = CvBridge()
self.depth_state = False
self.last_depth = 10.0
self.depth_counter = 0
self.top_left = (-1,-1)
self.top_right = (-1,-1)
self.bottom_right = (-1,-1)
self.bottom_left = (-1,-1)
self.x = (0,0)
self.y = (0,0)
self.pixel_length = 0
self.pixel_depth = 10.0
self.routine = False
#ros node related
rospy.init_node("turtle_control", anonymous=True)
#update rate can be increased
self.rate = rospy.Rate(30)
#Sub init
self.rgb_sub = rospy.Subscriber(astra_rgb_topic, Image, self.callback_rgb)
self.depth_sub = rospy.Subscriber(astra_depth_topic, Image, self.callback_depth)
#finding specific port for arduino communication
def init_serial(self):
for com in range(0,4):
#subprocess.run(["fuser", "/dev/ttyACM"+str(com), "-k"])
try:
port = DEVICE+str(com)
baud = BAUD
board = serial.Serial(port, baud)
board.close()
break
except:
pass
return com
#we wait for both publishers, camera topics, to send information
def wait_publishers(self, astra_rgb_topic, astra_depth_topic):
while True:
if any(astra_rgb_topic in topic_list for topic_list in rospy.get_published_topics()) and any(astra_depth_topic in topic_list for topic_list in rospy.get_published_topics()):
break
print("Waiting for {} and {} to start.".format(astra_rgb_topic, astra_depth_topic))
rospy.sleep(1)
def callback_rgb(self, data):
try:
rgb_image = self.rgb_bridge.imgmsg_to_cv2(data, "bgr8")
#if self.verbose == "window" or self.verbose == "both": cv2.rotate(rgb_image, cv2.ROTATE_180, rgb_image)
(self.h, self.w) = rgb_image.shape[:2]
except CvBridgeError as e:
print(e)
#if self.fresh_start is True:
# print("I HAD A NIGHTMARE, THE WOLF EATING THE RAVEN")
# self.t.linear.x = 0.2 * self.vel_fac
# while(time.time() - self.search_time) < 1:
# self.pub.publish(self.t)
# self.fresh_start = False
# self.search_time = time.time()
if not self.routine:
if self.verbose == "terminal" or self.verbose == "both": print("NO SEARCH JUST DETECT")
(corners, ids, rejected) = cv2.aruco.detectMarkers(rgb_image, self.arucoDict, parameters = self.arucoParams)
if corners and self.search != SEARCH[0]:
for id_x in ids:
if self.search == SEARCH[0]:
break
elif id_x in WHITELIST_OBJECT and self.search == SEARCH[1]:
self.target_id = id_x
self.search = SEARCH[0]
#print("TARGET ID = " + str(self.target_id))
break
elif id_x in WHITELIST_PLACE and self.search == SEARCH[2]:
if (self.last_id == WHITELIST_OBJECT[0] and id_x == WHITELIST_PLACE[0]) or (self.last_id == WHITELIST_OBJECT[1] and id_x == WHITELIST_PLACE[1]) or (self.last_id == WHITELIST_OBJECT[2] and id_x == WHITELIST_PLACE[2]):
self.target_id = id_x
self.search = SEARCH[0]
break
else:
self.search = SEARCH[2]
pass
if self.search == SEARCH[1]:
if self.verbose == "terminal" or self.verbose == "both": print("SEARCH TIME")
if (time.time() - self.search_time) < 41.8879:
if self.verbose == "terminal" or self.verbose == "both": print("LOOKING AROUND")
self.t.linear.x = 0.00 * self.vel_fac
self.t.angular.z = 0.15 * self.vel_fac
else:
if self.verbose == "terminal" or self.verbose == "both":print("TIMES UP")
self.t.linear.x = 0.1 * self.vel_fac
self.t.angular.z = 0.0 * self.vel_fac
self.search_time = time.time()
self.pub.publish(self.t)
if self.verbose == "terminal" or self.verbose == "both": print("DID I FIND THE ANSWER TO ALL MY QUESTIONS OR GRAVENIMAGE OF ME?")
(corners, ids, rejected) = cv2.aruco.detectMarkers(rgb_image, self.arucoDict, parameters = self.arucoParams)
if corners:
for id_x in ids:
if id_x in WHITELIST_OBJECT:
self.target_id = id_x
self.search = SEARCH[0]
break
elif self.search == SEARCH[0]:
(corners, ids, rejected) = cv2.aruco.detectMarkers(rgb_image, self.arucoDict, parameters = self.arucoParams)
if corners:
if self.verbose == "terminal" or self.verbose == "both": print("I SAW SOMETHING")
x = np.where(ids == self.target_id)
if len(x[0]) > 0:
fitting_corners = corners[x[0][0]]
rgb_image = self.markDetected(rgb_image, fitting_corners)
self.lastConernerTime = time.time()
elif(self.lastConernerTime - time.time()) < 1./2:
self.depth_state = False
if self.position is POSITIONS[0]:
if self.verbose == "terminal" or self.verbose == "both": print("I NEED TO GO LEFT!")
cv2.rectangle(rgb_image, (0,0), (20, self.h), (0,0,255), cv2.FILLED)
self.t.linear.x = 0.0 * self.vel_fac
self.t.angular.z = 0.15 * self.vel_fac
self.pub.publish(self.t)
elif self.position is POSITIONS[1]:
if self.verbose == "terminal" or self.verbose == "both": print("I NEED TO GO RIGHT")
cv2.rectangle(rgb_image, (self.w-20,0), (self.w, self.h), (0,0,255), cv2.FILLED)
self.t.linear.x = 0.0 * self.vel_fac
self.t.angular.z = -0.15 * self.vel_fac
self.pub.publish(self.t)
else:
if self.verbose == "terminal" or self.verbose == "both": print("LET ME CHECK STRAIGHT FORWARD")
self.t.linear.x = 0.1 * self.vel_fac
self.t.angular.z = 0.0 * self.vel_fac
self.pub.publish(self.t)
elif self.search == SEARCH[2]:
if self.verbose == "terminal" or self.verbose == "both": print("SEARCH TIME")
if (time.time() - self.search_time) < 41.8879:
if self.verbose == "terminal" or self.verbose == "both": print("LOOKING AROUND")
self.t.linear.x = 0.00 * self.vel_fac
self.t.angular.z = 0.15 * self.vel_fac
else:
if self.verbose == "terminal" or self.verbose == "both": print("TIMES UP")
self.t.linear.x = 0.1 * self.vel_fac
self.t.angular.z = 0.0 * self.vel_fac
self.search_time = time.time()
self.pub.publish(self.t)
if self.verbose == "terminal" or self.verbose == "both": print("DID I FIND THE ANSWER TO ALL MY QUESTIONS OR GRAVENIMAGE OF ME?")
(corners, ids, rejected) = cv2.aruco.detectMarkers(rgb_image, self.arucoDict, parameters = self.arucoParams)
if corners:
for id_x in ids:
if id_x in WHITELIST_PLACE:
if (self.last_id == WHITELIST_OBJECT[0] and id_x == WHITELIST_PLACE[0]) or (self.last_id == WHITELIST_OBJECT[1] and id_x == WHITELIST_PLACE[1]) or (self.last_id == WHITELIST_OBJECT[2] and id_x == WHITELIST_PLACE[2]):
self.target_id = id_x
self.search = SEARCH[0]
break
else:
self.search = SEARCH[2]
pass
else:
pass
#self.target_id = TARGET
#(corners, ids, rejected) = cv2.aruco.detectMarkers(rgb_image, self.arucoDict, parameters = self.arucoParams)
#if corners:
# for id_x in ids:
# if id_x in WHITELIST_OBJECT and SEARCH[1]:
# self.target_id = id_x
# self.search = SEARCH[0]
# break
#if self.verbose == "terminal" or self.verbose == "both": print("Routine initialised")
#some additional info on screen
if self.verbose == "window" or self.verbose == "both":
#id_str = "IDs: " + str(ids) + " Target_ID:" + str(self.target_id)
#cv2.putText(rgb_image, id_str, (10,30), cv2.FONT_HERSHEY_TRIPLEX, 1, (255,0,0), 2, cv2.LINE_8)
depth_str = "Depth_State:" + str(self.depth_state) + " Depth:" + str(self.last_depth)
cv2.putText(rgb_image, depth_str, (10,60), cv2.FONT_HERSHEY_TRIPLEX, 1, (255,0,0), 2, cv2.LINE_8)
info_str = "Search_State: " + str(self.search)
cv2.putText(rgb_image, info_str, (10,90), cv2.FONT_HERSHEY_TRIPLEX, 1, (255,0,0), 2, cv2.LINE_8)
self.rate.sleep()
if self.verbose == "window" or self.verbose == "both": cv2.imshow("Tutel", rgb_image)
cv2.waitKey(1)
def callback_depth(self, data):
if self.depth_state:
depth_image = self.depth_bridge.imgmsg_to_cv2(data, "passthrough")
#if self.verbose == "window" or self.verbose == "both": cv2.rotate(depth_image, cv2.ROTATE_180, depth_image)
#x and y are swapped, because
#print(str(self.top_left[0]) + " " + str(self.top_right[0]) + " " + str(self.top_left[1]) + " " + str(self.bottom_right[1]))
#if (self.top_left[0] - self.bottom_left[0]) in range (-10,10):
# if self.top_left[0] < self.top_right[0]: self.x = (self.top_left[0],self.top_right[0])
# else: self.x = (self.top_right[0],self.top_left[0])
# if self.top_left[1] < self.bottom_left[1]: self.y = (self.top_left[1],self.bottom_left[1])
# else: self.y = (self.bottom_left[1],self.top_left[1])
#elif (self.top_left[0] - self.top_right[0]) in range (-10,10):
# if self.bottom_left[0] < self.top_left[0]: self.x = (self.bottom_left[0],self.top_left[0])
# else: self.x = (self.top_left[0],self.bottom_left[0])
# if self.bottom_left[1] < self.bottom_right[1]: self.y = (self.bottom_left[1],self.bottom_right[1])
# else: self.y = (self.bottom_right[1],self.bottom_left[1])
#self.pixel_length = (self.x[1] - self.x[0] + self.y[1] - self.y[0]) / 2
#Approximation function for the amount of marker side's pixel for a specific distance to the camera
#f(x)=2914.2987x^-1.0159, with x := distance between camera and marker. Values rounded down to 4 digits.
#self.pixel_depth = ((self.pixel_length/2914.29872964688)**(-1/1.01590290349592))*10 #*10 to get the depth value in mm as the depth image delivers them in mm
#self.pixel_length = (abs(self.top_left[0]-self.top_right[0]) + abs(self.top_left[1] - self.bottom_left[1]) + abs(self.top_right[1]-self.bottom_right[1]) + abs(self.bottom_right[0]-self.bottom_left[0]))/4
#self.pixel_depth = ((self.pixel_length/2675.4910012317)**(-1/0.993434027))*10
pixels = (abs(self.top_left[0]-self.top_right[0]), abs(self.top_left[1] - self.bottom_left[1]), abs(self.top_right[1]-self.bottom_right[1]), abs(self.bottom_right[0]-self.bottom_left[0]))
self.pixel_length = max(pixels)
if self.target_id in WHITELIST_OBJECT: self.pixel_depth = ((self.pixel_length/2858.4636643479)**(-1/1.0056840993))*10
elif self.target_id in WHITELIST_PLACE: self.pixel_depth = ((self.pixel_length/6256.74528964037)**(-1/1.02442049036119))*10
#self.pixel_depth = (self.pixel_depth + ((((self.x[1] - self.x[0] + self.y[1] - self.y[0]) / 2)/2914.29872964688)**(-1/1.01590290349592))*10)/2
depth_values = []
#M = ((self.x[0] + (self.x[1]-self.x[0])//2), (self.y[0] + (self.y[1]-self.y[0])//2))
#depth_values.append(depth_image[M[1]][M[0]])
#for i in range(self.x[0], self.x[1]):
#for j in range(self.y[0], self.y[1]):
#if depth_image[j][i] > self.min_threshold and depth_image[j][i] < self.max_threshold and depth_image[j][i] < self.pixel_depth:
#depth_values.append(depth_image[j][i])
for i in range(self.x[0], self.x[1]+1):
if depth_image[self.y[0]][i] > self.min_threshold and depth_image[self.y[0]][i] < self.max_threshold and depth_image[self.y[0]][i] < self.pixel_depth:
depth_values.append(depth_image[self.y[0]][i])
print(self.pixel_depth, depth_values, self.last_depth)
if self.pixel_depth > self.max_threshold:
if self.pixel_depth < self.last_depth or self.last_depth == 10:
self.last_depth = self.pixel_depth
else:
self.last_depth = self.last_depth
else:
if len(depth_values)>0 and ((max(depth_values) > self.min_threshold and max(depth_values) < self.last_depth) or self.last_depth == 10):
self.last_depth = max(depth_values)
elif (len(depth_values)>0 and max(depth_values) < self.min_threshold) or len(depth_values)<1:
self.last_depth = self.pixel_depth
else:
self.last_depth = self.last_depth
if self.verbose == "terminal" or self.verbose == "both": print(self.depth_counter, self.last_depth)
if (self.last_depth**2 - HEIGHT_CAMERA**2) < ARM_LENGTH**2:
self.depth_counter += 1
if self.depth_counter > 0:
self.t.linear.x = 0.0 * self.vel_fac
self.t.angular.z = 0.0 * self.vel_fac
self.pub.publish(self.t)
if self.verbose == "terminal" or self.verbose == "both": print(self.last_depth)
self.routine = True
if self.verbose == "terminal" or self.verbose == "both": print("Only a few cm")
#self.t.linear.x = 0.1 * self.vel_fac
#self.t.angular.z = 0.0 * self.vel_fac
self.position = POSITIONS[2]
self.depth_counter = 0
self.depth_state = False
#self.last_depth = 10.0
#start = time.time()
#while (time.time() - start) < 0.55:
# self.pub.publish(self.t)
#self.t.linear.x = 0.0 * self.vel_fac
#self.pub.publish(self.t)
if self.target_id in WHITELIST_OBJECT:
print("Grab")
x_coordinate = math.sqrt(self.last_depth**2 - HEIGHT_CAMERA**2) - CAMERA_TO_ARM
self.last_id = self.target_id
self.target_id = TARGET
self.move_arm(x_coordinate)
else:
print("Release")
self.last_id = TARGET
self.target_id = TARGET
self.release()
if self.verbose == "terminal" or self.verbose == "both": print("We reached our destination")
else:
self.depth_counter = 0
def markDetected(self, image, corners):
for markerCorner in corners:
(self.top_left, self.top_right, self.bottom_right, self.bottom_left) = markerCorner.reshape((4,2))
self.top_left = (int(self.top_left[0]), int(self.top_left[1]))
self.top_right = (int(self.top_right[0]), int(self.top_right[1]))
self.bottom_right = (int(self.bottom_right[0]), int(self.bottom_right[1]))
self.bottom_left = (int(self.bottom_left[0]), int(self.bottom_left[1]))
if (self.top_left[0] - self.bottom_left[0]) in range (-10,10):
if self.top_left[0] < self.top_right[0]: self.x = (self.top_left[0],self.top_right[0])
else: self.x = (self.top_right[0],self.top_left[0])
if self.top_left[1] < self.bottom_left[1]: self.y = (self.top_left[1],self.bottom_left[1])
else: self.y = (self.bottom_left[1],self.top_left[1])
elif (self.top_left[0] - self.top_right[0]) in range (-10,10):
if self.bottom_left[0] < self.top_left[0]: self.x = (self.bottom_left[0],self.top_left[0])
else: self.x = (self.top_left[0],self.bottom_left[0])
if self.bottom_left[1] < self.bottom_right[1]: self.y = (self.bottom_left[1],self.bottom_right[1])
else: self.y = (self.bottom_right[1],self.bottom_left[1])
cv2.line(image, self.top_left, self.top_right, (0,255,0), 2)
cv2.line(image, self.top_right, self.bottom_right, (0,255,0), 2)
cv2.line(image, self.bottom_right, self.bottom_left, (0,255,0), 2)
cv2.line(image, self.bottom_left, self.top_left, (0,255,0), 2)
self.depth_state = True
if self.last_depth > 1000:
if self.x[1] < self.w//2 - 80:
if self.verbose == "terminal" or self.verbose == "both": print("LEFT")
self.t.linear.x = 0.0
self.t.angular.z = 0.15
elif self.x[0] > self.w//2 + 80:
if self.verbose == "terminal" or self.verbose == "both": print("RIGHT")
self.t.linear.x = 0.0
self.t.angular.z = -0.15
else:
self.t.linear.x = 0.1
self.t.angular.z = 0.0
elif self.last_depth > 700:
if self.x[1] < self.w//2 - 50:
if self.verbose == "terminal" or self.verbose == "both": print("LEFT")
self.t.linear.x = 0.0
self.t.angular.z = 0.15
elif self.x[0] > self.w//2 + 50:
if self.verbose == "terminal" or self.verbose == "both": print("RIGHT")
self.t.linear.x = 0.0
self.t.angular.z = -0.15
else:
self.t.linear.x = 0.1
self.t.angular.z = 0.0
else:
marker_x = ((self.x[0] + (self.x[1]-self.x[0])//2 - 5), (self.x[0] + (self.x[1]-self.x[0])//2 + 5))
if marker_x[1] < self.w//2:
if self.verbose == "terminal" or self.verbose == "both": print("LEFT")
self.t.linear.x = 0.0
self.t.angular.z = 0.15
elif marker_x[0] > self.w//2:
if self.verbose == "terminal" or self.verbose == "both": print("RIGHT")
self.t.linear.x = 0.0
self.t.angular.z = -0.15
else:
self.t.linear.x = 0.1
self.t.angular.z = 0.0
self.pub.publish(self.t)
if self.w//2 - 50 > self.x[0]:
self.position = POSITIONS[0]
elif self.w//2 + 50 < self.x[1]:
self.position = POSITIONS[1]
else:
self.position = POSITIONS[2]
return image
def move_arm(self, x):
#grabbed =''
print("I AM HERE")
x_coordinate = int(x) + 20
print(x_coordinate)
#self.board.flush()
self.board.write(bytes("0 0 0", "utf-8"))
self.board.flush()
self.board.reset_input_buffer()
self.board.reset_output_buffer()
while self.board.in_waiting < 6:
pass
self.board.reset_input_buffer();
self.board.reset_output_buffer()
coordinates = str(x_coordinate) + " 0 -115"
print(coordinates)
self.board.write(bytes(coordinates, "utf-8"))
self.board.flush()
self.board.reset_output_buffer()
print("Messages send!")
if self.verbose == "terminal" or self.verbose == "both": print("move arm")
while self.board.in_waiting < 6:
pass
self.board.reset_input_buffer()
self.board.reset_output_buffer()
self.board.write(bytes("1 1 1","utf-8"))
self.board.flush()
self.board.reset_output_buffer()
while self.board.in_waiting < 6:
pass
self.board.reset_input_buffer()
self.search = SEARCH[2]
self.last_depth = 10.0
self.routine =False
print(self.routine)
def release(self):
#released = ''
self.board.reset_input_buffer()
self.board.reset_output_buffer()
self.board.write(bytes("1 1 1", "utf-8"))
while self.board.in_waiting < 6:
pass
self.board.write(bytes("-1 -1 -1", "utf-8"))
self.board.reset_input_buffer()
self.board.reset_output_buffer()
while self.board.in_waiting < 6:
pass
self.board.reset_input_buffer()
self.board.reset_output_buffer()
if self.verbose == "terminal" or self.verbose == "both": print("release object")
self.search = SEARCH[1]
self.last_depth = 10.0
self.routine = False
print(self.routine)
def main():
if len(sys.argv) < 4 or len(sys.argv) > 5:
print("Please give the following arguments <turtlebot-navi-topic> and <camera-img-topic> and <camera-depth-topic> and optional <verbose-flag>")
print("Like: tutel_max_value_pure.py /cmd_vel_mux/input/navi /camera/color/image_raw /camera/depth/image_raw <verbose-flag>")
return 1
elif len(sys.argv) == 4:
ic = tutel(str(sys.argv[1]),str(sys.argv[2]),str(sys.argv[3]))
else:
ic = tutel(str(sys.argv[1]), str(sys.argv[2]), str(sys.argv[3]), str(sys.argv[4]))
try:
rospy.spin()
except KeyboardInterrupt:
print("Shutting down")
cv2.destroyAllWindows()
if __name__ == "__main__":
main()