问题
I have an image similar to the following. I want to separate two numbers 7
and 4
as shown in the image, in that I want to have a bounding box for each of these two objects.
How could I do this with OpenCV? I have no idea, how could I do this and was thinking if there is some way by using Sobel operator. The only thing that I tired was getting the Sobel.
s = cv2.Sobel(img, cv2.CV_64F,1,0,ksize=5)
but have no idea on how to proceed from here.
回答1:
To segment and detect figures in an image, the main idea is as follows:
- Convert image into grayscale using cv2.cvtColor
- Blur image with cv2.GaussianBlur
- Find edges with cv2.Canny
- Find contours with cv2.findContours and sort from left-to-right using imutils.contours.sort_contours() to ensure that when we iterate through contours, they are in the correct order
- Iterate through each contour
- Obtain bounding rectangle using cv2.boundingRect
- Find ROI of each contour with Numpy slicing
- Draw bounding box rectangle using cv2.rectangle
Canny Edge Detection
Detected Contours
Cropped and saved ROIs
Output
Contours Detected: 2
Code
import numpy as np
import cv2
from imutils import contours
# Load image, grayscale, Gaussian blur, Canny edge detection
image = cv2.imread("1.png")
original = image.copy()
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(gray, (3,3), 0)
canny = cv2.Canny(blurred, 120, 255, 1)
# Find contours
contour_list = []
ROI_number = 0
cnts = cv2.findContours(canny, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
cnts, _ = contours.sort_contours(cnts, method="left-to-right")
for c in cnts:
# Obtain bounding rectangle for each contour
x,y,w,h = cv2.boundingRect(c)
# Find ROI of the contour
roi = image[y:y+h, x:x+w]
# Draw bounding box rectangle, crop using Numpy slicing
cv2.rectangle(image,(x,y),(x+w,y+h),(0,255,0),3)
ROI = original[y:y+h, x:x+w]
cv2.imwrite('ROI_{}.png'.format(ROI_number), ROI)
contour_list.append(c)
ROI_number += 1
print('Contours Detected: {}'.format(len(contour_list)))
cv2.imshow("image", image)
cv2.imshow("canny", canny)
cv2.waitKey()
回答2:
Follow the steps:
- Convert the image into grayscale.
- Use thresholding to convert image into a binary image, in your problem I think adaptive gausian will be most beneficial to use.
- Apply contour detection and then you can make bounding box around contours.
You may need to filter contours based on size or position.
来源:https://stackoverflow.com/questions/55782857/how-to-detect-separate-figures-in-an-image