ROS Resources: Documentation | Support | Discussion Forum | Index | Service Status | ros @ Robotics Stack Exchange
Ask Your Question
0

How to break and come of the for loop ?

asked 2014-06-27 04:34:01 -0600

jashanvir gravatar image

updated 2014-06-27 05:47:03 -0600

Hello guys ! I am working on Morse and ROS- Hydro version. I want to break and come out of the for loop when my flag is set to 1 ( and this flag is set in opencv part) once the flag is set, it should enter an another function and print 'flag is set' The following is the code:-

#!/usr/bin/env python
import roslib
import sys
import time
import math
import rospy
import cv2
import time
#import cv2.cv as cv
import numpy as np
from std_msgs.msg import Float64
from geometry_msgs.msg import PoseStamped
from geometry_msgs.msg import Vector3
from geometry_msgs.msg import Twist
from geometry_msgs.msg import Wrench
from geometry_msgs.msg import Pose
from geometry_msgs.msg import Point
from sensor_msgs.msg import NavSatFix
from sensor_msgs.msg import CameraInfo
from sensor_msgs.msg import Image
from sensor_msgs.msg import RegionOfInterest
from cv_bridge import CvBridge, CvBridgeError
from rospy.numpy_msg import numpy_msg
a=0
b=0
c=0
timer = 0
flag =0
#def permanent_stop():
#   my_value = 1
#   stop(x=5)
#   return 1
def bridge_opencv():
        image_pub = rospy.Publisher("quadrotor/videocamera1/camera_info",Image)

            cv2.namedWindow("Image window", 1)

        image_sub = rospy.Subscriber("quadrotor/videocamera1/image",Image, callback)


def callback(data):
        global timer
        global dis
        global my_var1
        global my_var2
        global my_var3
        global a
        global b
        global c
        bridge = CvBridge()
        try:
            cv_image = bridge.imgmsg_to_cv2(data, "bgr8")
        except CvBridgeError, e:
            print e
        (rows,cols,channels) = cv_image.shape
        if cols > 60 and rows > 60 :
            cv2.circle(cv_image, (50,50), 10, 255)
        #converting bgr to hsv  
        hsv=cv2.cvtColor(cv_image,cv2.COLOR_BGR2HSV)
        # define range of blue color in HSV
            lower_blue = np.array([60,0,0],dtype=np.uint8)
            upper_blue = np.array([255,255,255],dtype=np.uint8)
        # Threshold the HSV image to get only blue colors
            mask = cv2.inRange(hsv, lower_blue, upper_blue)
        new_mask = mask.copy()
        # Bitwise-AND mask and original image
            res = cv2.bitwise_and(cv_image,cv_image, mask= mask)
        #removing noise 
        kernel = np.ones((12,12),np.uint8)
        new_mask = cv2.morphologyEx(new_mask, cv2.MORPH_CLOSE, kernel)
        new_mask = cv2.morphologyEx(new_mask, cv2.MORPH_OPEN, kernel)
        contours, hierarchy = cv2.findContours(new_mask,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
        cv2.drawContours(cv_image, contours, -1, (0,0,0), 3)

        if(contours):
            cv2.drawContours(cv_image, contours, -1, (0,0,0), 3)
            cnt = contours[0]
            area = cv2.contourArea(cnt)
            #print area 
            if area > 6000:
                print('i found the object')
                dis = timer*0.4
                #print 'dis',dis
                my_var1= a+dis
                my_var2 = b
                my_var3 = c
                flag = 1
                coorda = Float64()
                coordb = Float64()
                coordc = Float64()
                #my_value2 = False
        cv2.imshow('mask',mask)
            cv2.imshow('res',res)
        cv2.imshow("Image window", cv_image)
        cv2.waitKey(3)

def stop(x):
        now=time.time()
        global timer
        print 'stop'    
        cmd = rospy.Publisher("/quadrotor/rotorcraftvelocity", Twist)   
        while timer !=x:
            motion = Twist()
            motion.linear.x = +0.0
            motion.linear.y = +0.0
            motion.linear.z = +0.0
            cmd.publish(motion) 
            end = time.time()
            timer = round(end-now)

def left():
        now = time.time()
        global timer
        print 'left'
        global b
        cmd = rospy.Publisher("/quadrotor/rotorcraftvelocity", Twist)   
        while timer !=10:   
            motion = Twist()        
            motion.linear.y = -0.4
            cmd.publish(motion)     
            end = time.time()
            timer = round(end-now)
        b = b-4 

def right ...
(more)
edit retag flag offensive close merge delete

2 Answers

Sort by ยป oldest newest most voted
0

answered 2014-06-30 07:51:35 -0600

jashanvir gravatar image

I have tried this and it worked for me.

#!/usr/bin/env python
import roslib
import sys
import time
import math
import rospy
import cv2
import time
#import cv2.cv as cv
import numpy as np
from std_msgs.msg import Float64
from geometry_msgs.msg import PoseStamped
from geometry_msgs.msg import Vector3
from geometry_msgs.msg import Twist
from geometry_msgs.msg import Wrench
from geometry_msgs.msg import Pose
from geometry_msgs.msg import Point
from sensor_msgs.msg import NavSatFix
from sensor_msgs.msg import CameraInfo
from sensor_msgs.msg import Image
from sensor_msgs.msg import RegionOfInterest
from cv_bridge import CvBridge, CvBridgeError
from rospy.numpy_msg import numpy_msg
a=0
b=0
c=0
timer = 0

def bridge_opencv():
        image_pub = rospy.Publisher("quadrotor/videocamera1/camera_info",Image)
            cv2.namedWindow("Image window", 1)
        image_sub = rospy.Subscriber("quadrotor/videocamera1/image",Image, callback)


def callback(data):
        global timer
        global dis
        global my_var1
        global my_var2
        global my_var3
        global a
        global b
        global c
        global flag

        bridge = CvBridge()
        try:
            cv_image = bridge.imgmsg_to_cv2(data, "bgr8")
        except CvBridgeError, e:
            print e
        (rows,cols,channels) = cv_image.shape
        if cols > 60 and rows > 60 :
            cv2.circle(cv_image, (50,50), 10, 255)
        #converting bgr to hsv  
        hsv=cv2.cvtColor(cv_image,cv2.COLOR_BGR2HSV)
        # define range of blue color in HSV
            lower_blue = np.array([60,0,0],dtype=np.uint8)
            upper_blue = np.array([255,255,255],dtype=np.uint8)
        # Threshold the HSV image to get only blue colors
            mask = cv2.inRange(hsv, lower_blue, upper_blue)
        new_mask = mask.copy()
        # Bitwise-AND mask and original image
            res = cv2.bitwise_and(cv_image,cv_image, mask= mask)
        #removing noise 
        kernel = np.ones((12,12),np.uint8)
        new_mask = cv2.morphologyEx(new_mask, cv2.MORPH_CLOSE, kernel)
        new_mask = cv2.morphologyEx(new_mask, cv2.MORPH_OPEN, kernel)
        contours, hierarchy = cv2.findContours(new_mask,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
        cv2.drawContours(cv_image, contours, -1, (0,0,0), 3)
        if(contours):
            cv2.drawContours(cv_image, contours, -1, (0,0,0), 3)
            cnt = contours[0]
            area = cv2.contourArea(cnt)
            #print area 
            if area > 500:
                dis = timer*0.4
                my_var1= a+dis
                my_var2 = b
                my_var3 = c
                flag = 1

        cv2.imshow('mask',mask)
            cv2.imshow('res',res)
        cv2.imshow("Image window", cv_image)
        cv2.waitKey(3)

def stop(x):
        global flag
        now=time.time()
        global timer
        print 'stop'    
        cmd = rospy.Publisher("/quadrotor/rotorcraftvelocity", Twist)   
        while timer !=x:
            motion = Twist()
            motion.linear.x = +0.0
            motion.linear.y = +0.0
            motion.linear.z = +0.0
            cmd.publish(motion) 
            end = time.time()
            timer = round(end-now)

def left():
        global flag
        now = time.time()
        global timer
        print 'left'
        global b
        cmd = rospy.Publisher("/quadrotor/rotorcraftvelocity", Twist)   
        while timer !=10:
            if flag !=1:    
                motion = Twist()        
                motion.linear.y = -0.4
                cmd.publish(motion)     
                end = time.time()
                timer = round(end-now)
            if flag ==1:
                print 'flag', flag
                print('i was here')
                break
        if flag !=1:
            b = b-4 

def right():
        global flag
        now=time.time()
        global timer
        print 'right'
        global b
        cmd = rospy.Publisher("/quadrotor/rotorcraftvelocity", Twist)
        while timer !=5:
            if flag !=1:                
                motion = Twist()
                motion.linear.y = +0.4
                cmd.publish(motion) 
                end = time.time()
                timer = round(end-now)
            if flag == 1:
                print 'flag', flag
                print('i was here')
                break
        if flag !=1 ...
(more)
edit flag offensive delete link more
3

answered 2014-06-27 05:03:26 -0600

ct2034 gravatar image

This is more of a general programming question. Maybe better try it here: http://stackoverflow.com But I would suggest to use a while loop instead. You can use break there or design your condition accordingly. https://wiki.python.org/moin/WhileLoop

edit flag offensive delete link more

Comments

Thanks a lot for your suggestion ! I thought I have problem in opencv function as the flag is not set in there.

jashanvir gravatar image jashanvir  ( 2014-06-27 05:34:29 -0600 )edit

I have one doubt. Does the callback or bridge_opencv() acts like thread. Because when run the code. The flag is set to 1 inside it but it somehow does not remain one when it comes out of it.

jashanvir gravatar image jashanvir  ( 2014-06-27 06:01:22 -0600 )edit
1

what do you mean by thread? Whether its running synchronous or not? I think you bridge_opencv() runs synchronous when it's called (in the same thread). And the callback is called asynchronous (in another thread. But please don't quote my on that. Maybe someone else has a better idea.

ct2034 gravatar image ct2034  ( 2014-06-27 07:00:09 -0600 )edit

Question Tools

1 follower

Stats

Asked: 2014-06-27 04:34:01 -0600

Seen: 2,243 times

Last updated: Jun 30 '14