Files
2024-03-04 16:22:37 +01:00

164 lines
7.1 KiB
Python

#!/usr/bin/env python
#pip3 install pencv-python3==4.9.0.80
#pip3 install rospy
from __future__ import print_function
import roslib
import sys
import rospy
import cv2
import time
import numpy as np
from std_msgs.msg import String
from sensor_msgs.msg import Image
from cv_bridge import CvBridge, CvBridgeError
from geometry_msgs.msg import Twist
class marker_attacker():
def wait_for_subscribers(self):
while self.pub.get_num_connections() == 0:
print("Waiting for subscriber on {}".format(self.pub.name))
rospy.sleep(1)
if rospy.is_shutdown():
raise Exception("Got shutdown request before subscribers connected")
def wait_for_publisher(self,astra_camera_rgb_topic,astra_camera_depth_topic):
while 1:
x = rospy.get_published_topics()
if any(astra_camera_depth_topic in subl for subl in x) and any(astra_camera_depth_topic in subl for subl in x):
break
print("Waiting for {} and {}".format(astra_camera_rgb_topic,astra_camera_depth_topic))
rospy.sleep(1)
def say_im_here(self):
rate = rospy.Rate(10) # 10hz
pub = rospy.Publisher('infoA', String, queue_size=10)
for x in range(0, 30):
hello_str = "IMHERE"
rospy.loginfo(hello_str)
pub.publish(hello_str)
rate.sleep()
def __init__(self, turlte_bot_topic : str, astra_camera_rgb_topic : str, astra_camera_depth_topic : str ,speed_emul : float = 1, start_id : int = 1):
self.speed_mul = speed_emul
self.target_id = start_id #We target one tag at a time
self.arucoDict = cv2.aruco.getPredefinedDictionary(cv2.aruco.DICT_ARUCO_ORIGINAL)
self.arucoParams = cv2.aruco.DetectorParameters_create()
self.maxMinDepth = 0.5
### For turtle controll
self.pub = rospy.Publisher(turlte_bot_topic, Twist, queue_size=1)
# self.wait_for_subscribers()
self.wait_for_publisher(astra_camera_rgb_topic,astra_camera_depth_topic)
self.t = Twist()
self.leftright = 0
self.lastConernerTime = time.time()
self.bridge = CvBridge()
rospy.init_node("turtle_control", anonymous=True)
self.rate = rospy.Rate(15) # update rate can be increased
self.depth_point = (-1,-1) #This is the point from where we get the depth
self.last_depth = 10 #This is the last depth from the depth_point
self.depth_counter = 0 #Make sure we are really there by counting how many time we got this result
self.rState = 0
self.image_sub = rospy.Subscriber(
astra_camera_rgb_topic, Image, self.callback_rgb
)
self.depth_bridge = CvBridge()
self.depth_image_sub = rospy.Subscriber(astra_camera_depth_topic,Image,self.callback_depth)
### Markers haven been detected, now do something
def markDetected(self, img, corners):
thresh_left = self.w//2 - 100
thresh_right = self.w//2 + 100
for markerCorner in corners:
(top_left, top_right, bottom_right, bottom_left) = markerCorner.reshape((4,2))
top_left = (int(top_left[0]), int(top_left[1]))
top_right = (int(top_right[0]), int(top_right[1]))
bottom_right = (int(bottom_right[0]), int(bottom_right[1]))
bottom_left = (int(bottom_left[0]), int(bottom_left[1]))
cv2.line(img, top_left, bottom_right, (0,255,0), 2)
cv2.line(img, top_right, bottom_left, (0,255,0), 2)
self.depth_point = (int((top_left[0] + bottom_right[0]) / 2), int((top_left[1] + bottom_right[1]) / 2))
cv2.circle(img, self.depth_point, 8, (0,0,255), -1)
self.lastMarkerPos = ((top_left),(bottom_right))
if ((top_left[0] > thresh_left and top_left[0] < thresh_right) or
(top_right[0] > thresh_left and top_right[0] < thresh_right) or
(bottom_left[0] > thresh_left and bottom_left[0] < thresh_right) or
(bottom_right[0] > thresh_left and bottom_right[0] < thresh_right)):
self.t.linear.x = 0.1 * self.speed_mul
self.t.angular.z = 0.0
self.pub.publish(self.t)
elif(top_right[0] < thresh_left or
bottom_right[0] < thresh_left):
self.t.linear.x = 0.0
self.t.angular.z = 0.3 * self.speed_mul
self.pub.publish(self.t)
elif(top_left[0] > thresh_right or
bottom_left[0] > thresh_right):
self.t.linear.x = 0.0
self.t.angular.z = -0.3 * self.speed_mul
self.pub.publish(self.t)
if int(self.w / 2) > top_left[0]:
self.leftright = 1
elif self.w - int(self.w / 2) < top_left[0]:
self.leftright = 2
return img
def callback_rgb(self, data):
try:
cv_image = self.bridge.imgmsg_to_cv2(data, "bgr8")
(self.h, self.w) = cv_image.shape[:2]
except CvBridgeError as e:
print(e)
#(rows, cols, channels) = cv_image.shape
(corners, ids, rejected) = cv2.aruco.detectMarkers(
cv_image, self.arucoDict, parameters=self.arucoParams
)
if self.rState == 0:
#This is a searching state, we are searching for right tag
self.t.linear.x = 0.0
self.t.angular.z = 0.4 * self.speed_mul
self.pub.publish(self.t)
if corners:
i = np.where(ids == self.target_id)
if len(i[0]) > 0:
self.rState = 1
elif self.rState == 1:
#####
# verify *at least* one ArUCo marker was detected
if corners:
#Now seleted the corners of the tag with the right id
i = np.where(ids == self.target_id)
if len(i[0]) > 0:
fitting_corners = corners[i[0][0]]
cv_image = self.markDetected(cv_image, fitting_corners)
self.lastConernerTime = time.time()
elif (self.lastConernerTime - time.time()) < 1./2:
self.depth_point = (-1,-1) #Indicates that we dont need depth to be processed
if self.leftright == 1:
#cv2.rectangle(cv_image, (0, 0), (20, self.h), (0,0,255), cv2.FILLED)
self.t.linear.x = 0.0
self.t.angular.z = 0.3 * self.speed_mul
self.pub.publish(self.t)
elif self.leftright == 2:
#cv2.rectangle(cv_image, (self.w-20, 0), (self.w, self.h), (0,0,255), cv2.FILLED)
self.t.linear.x = 0.0
self.t.angular.z = -0.3 * self.speed_mul
self.pub.publish(self.t)
#Give some additional informations
idString = "IDs:" + str(ids) + " TargetID:" + str(self.target_id)
# cv2.putText(cv_image, idString, (10,30), cv2.FONT_HERSHEY_TRIPLEX, 1, (255, 0, 0), 2, cv2.LINE_8)
depthString = "DepthPoint:" + str(self.depth_point[0]) +"x" +str(self.depth_point[1]) + " Depth:" + str(self.last_depth)