Ask Your Question

Revision history [back]

How to color the pixels in an image depending on whether they are inside/outside a zone/circle?

I am converting an input ROS image to OpenCV, drawing a circle on the image, and removing points outside the circle. I want to be able to color the pixels in the image depending on whether they fall outside or inside the circle (like a zone). I'd like the pixels inside the circle to be red, and the pixels ouside the circle to be green. This image clearly shows what I mean: I am currently getting the images on the left, but would like to get the images on the right.

I am attaching my code below. I have played around with the cv2.circle and cv2.rectangle functions, but have had trouble getting these to work. Thank you for your help!

depth_image = self.bridge.imgmsg_to_cv2(self.myImage, desired_encoding="passthrough") 
depth_image_noNaN = np.nan_to_num(depth_image,0)
self.oldDepthArray = np.array(depth_image_noNaN)
cv2.circle(self.oldDepthArray, (self.myImage.width/2, self.myImage.height/2), 130, (255,0,0), 4)

self.oldDepthArray.resize((self.myImage.height, self.myImage.width))
boundary_circle = np.zeros((self.myImage.height, self.myImage.width), np.uint8)
cv2.circle(boundary_circle, (self.myImage.width/2, self.myImage.height/2), zone_radius, (170,0,0), -1)
self.circleImage = self.bridge.cv2_to_imgmsg(self.oldDepthArray, encoding="passthrough")
self.pubCircleImage.publish(self.circleImage)

self.newDepthArray = cv2.bitwise_and(self.oldDepthArray, self.oldDepthArray, mask = boundary_circle)
self.newImage = self.bridge.cv2_to_imgmsg(self.newDepthArray, encoding="passthrough")
self.pubNewImage.publish(self.newImage)

image description