python - Problems detecting cardboard boxes with OpenCV - Stack Overflow

admin2025-05-01  0

I am developing an application to detect cardboard boxes with a 3d camera. After rasterising the image to get a 2d image of a particular plane from the point cloud I got this. enter image description here

At the moment I am trying to filter by area and size.

This is part of the code

img = cv.cvtColor(imagen, cv.COLOR_BGR2GRAY)



# Apply GaussianBlur to reduce image noise if it is required
if is_reduce_noise:
   img = cv2.GaussianBlur(img, (5, 5), 0)
# Set total number of bins in the histogram
bins_num = 256

# Get the image histogram
hist, bin_edges = np.histogram(img, bins=bins_num)

# Get normalized histogram if it is required
if is_normalized:
    hist = np.divide(hist.ravel(), hist.max())

# Calculate centers of bins
bin_mids = (bin_edges[:-1] + bin_edges[1:]) / 2.

# Iterate over all thresholds (indices) and get the probabilities w1(t), w2(t)
weight1 = np.cumsum(hist)
weight2 = np.cumsum(hist[::-1])[::-1]

# Get the class means mu0(t)
mean1 = np.cumsum(hist * bin_mids) / weight1
# Get the class means mu1(t)
mean2 = (np.cumsum((hist * bin_mids)[::-1]) / weight2[::-1])[::-1]

inter_class_variance = weight1[:-1] * weight2[1:] * (mean1[:-1] - mean2[1:]) ** 2

# Maximize the inter_class_variance function val
index_of_max_val = np.argmax(inter_class_variance)

threshold = bin_mids[:-1][index_of_max_val]
print("Otsu's algorithm implementation thresholding result: ", threshold)

otsu_threshold, image_result = cv2.threshold(img, int(threshold), 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU,)
print("Obtained threshold: ", otsu_threshold)
kernel_closing_busqueda = np.ones((5, 5), np.uint8)
edges = cv2.Canny(img, otsu_threshold*0.5, otsu_threshold, apertureSize=3,L2gradient=True)
closing = cv2.morphologyEx(edges, cv2.MORPH_CLOSE, kernel_closing_busqueda)

The problem is that I can't detect the boxes because the texts they have are joined to the outlines. Can you help me with this?

Best regards David

转载请注明原文地址:http://www.anycun.com/QandA/1746112305a91839.html