'OpenCV - Find subcontour in a contour
i want to use the OpenCV Match Shapes-Function to find a known Contour in a larger image like in this example (3. Match Shapes)
https://docs.opencv.org/4.x/d5/d45/tutorial_py_contours_more_functions.html
The problem is that I do not know the complete contour, but only a part of it. In the attached example, for example, it would be only a quarter of the star.
Hier is an example code
import cv2 as cv
import imutils
import cv2 as cv2
import numpy as np
from matplotlib import pyplot as plt
plt.rcParams['figure.figsize'] = [30, 15]
img = cv.imread('lala.png')
org = img.copy()
img_grayscale = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
ret,thresh = cv2.threshold(img_grayscale,25,255,cv2.THRESH_BINARY)
#find sub contour
mask = np.zeros(thresh.shape,np.uint8)
mask[330:550,3:172] = thresh[330:550,3:172]
contours, hierarchy = cv2.findContours(mask,cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE)
plt.imshow(cv2.cvtColor(mask, cv2.COLOR_BGR2RGB)), plt.show()
cv.drawContours(img, contours, -1, (0,255,0), 3)
plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB)), plt.show()
#find all contours
ret,thresh = cv2.threshold(img_grayscale,25,255,cv2.THRESH_BINARY)
all_contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE)
#find match
ret = 1
for cnt in all_contours:
ret_new = cv2.matchShapes(cnt, contours[0] ,1,0.0)
if ret_new < ret:
ret = ret_new
matching_contour = cnt
cv.drawContours(org, matching_contour, -1, (0,255,0), 3)
plt.imshow(cv2.cvtColor(org, cv2.COLOR_BGR2RGB)), plt.show()
Do you have any idea how I can solve this? The Contour Matcher does not seem to support this function
The whole image This is the whole image in which I have to find a choosen sub-contour
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
