I have images loaded with cv2 in python. After detecting the edges using cv2.Canny I…
- User
I have images loaded with cv2 in python. After detecting the edges using cv2.Canny I want to draw boxes around the objects in the image. Give me an example in python.
- Assistant
Sure! Here's an example in Python:
pyimport cv2 # Load image and convert to grayscale img = cv2.imread('your_image.jpg') gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # Perform Canny edge detection edges = cv2.Canny(gray, 100, 200) # Find contours of objects in the image contours, hierarchy = cv2.findContours(edges, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) # Draw bounding boxes around each object for cnt in contours: x,y,w,h = cv2.boundingRect(cnt) cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,0),2) # Display result cv2.imshow('Image with bounding boxes', img) cv2.waitKey(0) cv2.destroyAllWindows()In this code, we first load the image and convert it to grayscale. We then use the
cv2.Canny()function to detect edges in the image. Next, we use to find the contours of objects in the image. Finally, we loop through each contour and use to draw a bounding box around the object.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.