Files
BP_Gripper_Control_WS_23_24/tiefeXpixel/depth_reader.py
T
2024-02-27 15:29:30 +01:00

194 lines
8.4 KiB
Python

#!/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
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 = 0
DEPTH = 400
POSITIONS = ["left", "right", "middle"]
DEVICE = 'dev/ttyACM'
BAUD = 9600
class tutel():
def __init__(self, astra_rgb_topic : str, astra_depth_topic : str, 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 0 at the beginning
self.target_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 depth we recognize, still testing for values!
self.maxMinDepth = DEPTH
#cv related
#rgb related
self.lastConernerTime = time.time()
self.rgb_bridge = CvBridge()
self.search = True
#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.number_of_operations = 0
self.number_of_pixels = 0
#ros node related
rospy.init_node("turtle_control", anonymous=True)
#update rate can be increased
self.rate = rospy.Rate(15)
#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)
#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")
cv2.rotate(rgb_image, cv2.ROTATE_180, rgb_image)
(self.h, self.w) = rgb_image.shape[:2]
except CvBridgeError as e:
print(e)
(corners, ids, rejected) = cv2.aruco.detectMarkers(rgb_image, self.arucoDict, parameters = self.arucoParams)
if corners:
for id_x in ids:
if id_x != 0:
self.target_id = id_x
break
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
#some additional info on screen
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)
pixel_str = "Number_of_pixel:" + str(self.number_of_pixels)
cv2.putText(rgb_image, pixel_str, (10,90), cv2.FONT_HERSHEY_TRIPLEX, 1, (255,0,0), 2, cv2.LINE_8)
cv2.line(rgb_image, (self.w//2, 0), (self.w//2, self.h), (0,255,0), 2)
self.rate.sleep()
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")
cv2.rotate(depth_image, cv2.ROTATE_180, depth_image)
if self.depth_counter == 0:
#pass
self.last_depth = 10.0
x = (0,0)
y = (0,0)
#x and y are swapped, because
if (self.top_left[0] - self.bottom_left[0]) in range (-10,10):
if self.top_left[0] < self.top_right[0]: x = (self.top_left[0],self.top_right[0])
else: x = (self.top_right[0],self.top_left[0])
if self.top_left[1] < self.bottom_left[1]: y = (self.top_left[1],self.bottom_left[1])
else: 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]: x = (self.bottom_left[0],self.top_left[0])
else: x = (self.top_left[0],self.bottom_left[0])
if self.bottom_left[1] < self.bottom_right[1]: y = (self.bottom_left[1],self.bottom_right[1])
else: y = (self.bottom_right[1],self.bottom_left[1])
depth_values = []
for i in range(x[0], x[1]):
self.number_of_pixels += 1
for j in range(y[0], y[1]):
if depth_image[j][i] > self.maxMinDepth:
depth_values.append(depth_image[j][i])
if len(depth_values)>0 and ((max(depth_values) > self.last_depth-100 and max(depth_values) < self.last_depth+100) or self.last_depth == 10):
self.last_depth = max(depth_values)
print(max(depth_values))
else:
self.last_depth = self.last_depth
lengths = [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])]
#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
pixel_length = max(lengths)
print(self.last_depth, self.number_of_pixels, pixel_length)
self.number_of_operations = 0
self.number_of_pixels = 0
pixel_length = 0
#cv2.imshow("Tutel_Depth", depth_image)
if self.last_depth < self.maxMinDepth and self.last_depth != 0:
self.depth_counter += 1
if self.depth_counter > 0:
self.depth_state = False
self.last_depth = 10.0
self.depth_counter = 0
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]))
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
return image
def move_arm(self):
self.s.write('1'.encode('utf-8'))
time.sleep(1)
def main():
if len(sys.argv)!=3:
print("Please give the following arguments <turtlebot-navi-topic> and <camera-img-topic> and <camera-depth-topic>")
print("Like: depth_reader.py /camera/rgb/image_raw /camera/depth/image_raw")
return 1
ic = tutel(str(sys.argv[1]),str(sys.argv[2]))
try:
rospy.spin()
except KeyboardInterrupt:
print("Shutting down")
cv2.destroyAllWindows()
if __name__ == "__main__":
main()