[
这是我需要进行轮廓检测的图像。我需要绘制矩形内部和外部的字符轮廓,但不需要矩形本身。我附加的第二张图片是所需的输出。
这是我迄今为止尝试过的方法:
import cv2
# Read the image
image = cv2.imread('fig1.jpg')
# Convert the image to grayscale
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# Apply histogram equalization to enhance contrast
equalized = cv2.equalizeHist(gray)
# Apply Gaussian blur to the equalized image
blurred = cv2.GaussianBlur(equalized, (5, 5), 0)
# Apply Laplacian operator to detect edges
edges = cv2.Laplacian(blurred, cv2.CV_64F)
# Apply thresholding to create a binary image
_, edges_binary = cv2.threshold(edges, 20, 255, cv2.THRESH_BINARY)
# Convert edges_binary to the appropriate data type (CV_8UC1)
edges_binary = edges_binary.astype(np.uint8)
# Find contours of the edges
contours, _ = cv2.findContours(edges_binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# Draw the sides of the rectangle (for visualization)
cv2.drawContours(image, contours, -1, (255, 255, 255), 2)
# Get the bounding box of the rectangle
x, y, w, h = cv2.boundingRect(contours[0])
# Omit the sides of the rectangle from the binary image
edges_binary[y:y+h, x:x+w] = 0
# Find contours in the modified binary image
contours, _ = cv2.findContours(edges_binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# Draw contours on the original image
cv2.drawContours(image, contours, -1, (0, 255, 0), 2)
# Display the result
cv2.imshow('Contour Detection', image)
cv2.waitKey(0)
cv2.destroyAllWindows()
我感觉好像我很亲近。我尝试了其他几种方法,但这种方法最接近所需的结果。我上周才学了 OpenCV,所以有人可以告诉我我还可以尝试什么吗?
您可以使用轮廓区域来避免大的外部矩形。尝试下面的代码。最终结果将具有字母和符号的边界框。希望这有帮助。
import cv2
import numpy as np
#READ IMAGE AND APPLY THRESHOLD
image = cv2.imread("letters.jpg")
grayscale_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
ret, thresholded_image = cv2.threshold(grayscale_image, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
#FIND THE CONTOURS IN IMAGE
contours, hierarchy = cv2.findContours(thresholded_image, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
contour_image = np.zeros_like(thresholded_image)
#SELECT CONTOURS WHICH ARE SMALL, LESS AREA COMPARED TO LARGE RECTANGLE
selected_ctr =[]
selected_bounding_rect = []
for ctr in contours:
if cv2.contourArea(ctr) < 1000: #ADJUST THIS ACCORDING TO YOUR NEED.
selected_ctr.append(ctr) #SELECT CONTOUR
selected_bounding_rect.append(cv2.boundingRect(ctr)) #GET BOUNDING BOX
#DRAW CONTOURS OF THE FOUND LETTERS AND SYMBOLS
cv2.drawContours(contour_image, selected_ctr, -1, 255, thickness=1)
cv2.imwrite("letters_ctr.jpg",contour_image) # SAVE CONTOUR IMAGE
#DRAW THE SELECTED RECTANGLES
for rect in selected_bounding_rect:
image_rect = cv2.rectangle(image, rect, (0, 255, 0) , 1)
cv2.imwrite("letters_rect.jpg",image_rect) #SAVE RECTANGLE DRAWN IMAGE
输出: