Есть ли способы сделать некоторые кадрирования в изображении на основе заданного шаблона? - PullRequest
0 голосов
/ 29 апреля 2020

У меня есть изображение горшков одинакового размера, пользователь должен обрезать область (скажем, он обрезает первый горшок (верхний левый угол)) изображения и в зависимости от рисунка, созданного или обрезанного пользователем Я должен автоматически выполнить другие обрезки и сохранить их координаты. Есть ли другой способ сделать это без сопоставления с шаблоном или вы думаете, что я могу улучшить свой код, чтобы сделать это только с сопоставлением с шаблоном?

До сих пор я пробовал с сопоставлением с шаблоном и сохранял координаты каждого соответствующего совпавшего, но, как вы можете видеть на прилагаемом изображении, результат не совсем удовлетворительный, потому что я не сопоставляю все банки и для некоторой области я рисую несколько прямоугольников только для одного банка (чем больше я опускаю порог). Мы высоко ценим любую помощь.

enter image description here

Вот мой код

# import necessary dependies
import cv2
import numpy as np

# Read the source image
img_rgb = cv2.imread('image.jpg')

# Convert the source image to gray
img_gray = cv2.cvtColor(img_rgb, cv.COLOR_BGR2GRAY)

# Read the pattern image designed by the user
template = cv2.imread('mattern.png',0)

# Get the shape of the pattern image
w, h = template.shape[::-1]

# Apply cv2 template matching functon
res = cv2.matchTemplate(img_gray,template,cv.TM_CCOEFF_NORMED)

# List of coordinates of the matched templates
list_coordinates = []
labeled_coordinates = []

# Threshold applied to the template matching
threshold = 0.55

# Apply the threshold to cv2 the template matching
loc = np.where( res >= threshold)

# Directory to save the matched templates (pattern)
s_dir = "s_img/"

# Counter to add in the name of the saved image
i = 1
for pt in zip(*loc[::-1]):
    # Draw a rectangle to area that satifies the condition
    cv2.rectangle(img_rgb, pt, (pt[0] + w, pt[1] + h), (0,0,255), 1)
    top_left = pt
    # Crop every matched templates (pattern)
    crop_img = img_rgb[top_left[1]:top_left[1] + h, top_left[0]:top_left[0]+w]
    bottom_right = (top_left[0] + w, top_left[1] + h)
    # Save the crop patterns for future use
    cv2.imwrite(s_dir+"crop_1_"+str(i)+".png", crop_img)
    # Label the coordinates for future use
    labeled_coordinates = ["crop_1_"+str(i), top_left[0], top_left[1], bottom_right[0], bottom_right[1]]
    # Add the coordinates in a list
    list_coordinates.append(labeled_coordinates)
    i += 1

cv2.imshow('template',template)
cv2.imshow('mathced',img_rgb)
cv2.waitKey(0)
cv2.destroyAllWindows()
...