Я использую findContours из openCV Чтобы обнаружить границу, я пытаюсь фильтровать по контурной области. Я вычисляю площадь, получая ограничивающий прямоугольник контура, а затем выполняя w*h. Я делаю это, потому что это обеспечивает лучшие результаты для моего приложения, чем использование контурной области, потому что я видел, что функция из openCV не вычисляет площадь в математическом смысле.
Но моя проблема в том, что я не понимаю, почему для некоторых изображений это работает:

а иногда и нет t

вот мой код:
def process(img):
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
img_canny = cv2.Canny(img_gray, 0, 1)
kernel = np.ones((9, 9), np.uint8)
img_dilate = cv2.dilate(img_canny, kernel, iterations=4)
img_res = cv2.erode(img_dilate, kernel, iterations=2)
#img_close = morphology.binary_closing(img_canny,None)
return img_res
#first phase of segmentation to remove outer border present in images
def perfect_phase_1(img_path):
img = cv2.imread(img_path)
img_copy = np.copy(img)
processed_img = process(img_copy)
contours, hierarchy = cv2.findContours(processed_img, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_NONE)
filter_contours = [ct for ct in contours if cv2.contourArea(ct) > 5000] #filter out small contours
areas = []
original_size = img_copy.shape
for ct in filter_contours:
x, y, w, h = cv2.boundingRect(ct)
areas.append(w * h)
#get the two biggest contours
top2 = []
for i in range(3):
if not filter_contours:
break # No more contours to process
largest_index = areas.index(max(areas))
largest_contour = filter_contours[largest_index]
# If this is the largest contour (i == 0), display its area at the top
if i == 0:
largest_area = areas[largest_index]
x, y, w, h = cv2.boundingRect(largest_contour)
cv2.putText(img_copy, f"Area: {largest_area}", (x, y - 10),
cv2.FONT_HERSHEY_SIMPLEX, 2, (0, 255, 0), 2)
top2.append(largest_contour)
# Remove the selected contour from the lists
del areas[largest_index]
del filter_contours[largest_index]
for ct in top2:
#print the contour hierarchy near to the contour
x, y, w, h = cv2.boundingRect(ct)
cv2.rectangle(img_copy, (x, y), (x + w, y + h), (0, 0, 255), 2)
return img_copy, top2
Подробнее здесь: https://stackoverflow.com/questions/791 ... -in-images