У меня есть это изображение, где мне нужно найти цветные фигуры в изображении
Мне нужны положения этих цветных фигур.
И мне нужно поместить эту обезьяну на зеленый треугольник
Мой код дает мне ошибку. Этот код может обнаруживать только черный цвет, но он выдает ошибку.
# import the necessary packages
import numpy as np
import argparse
import cv2
# construct the argument parse and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image", help = "path to the image file")
args = vars(ap.parse_args())
# load the image
image = cv2.imread(args["image"])
# find all the shapes in the image
lower = np.array([0, 0, 0])
upper = np.array([15, 15, 15])
shapeMask = cv2.inRange(image, lower, upper)
# find the contours in the mask
(cnts, _) = cv2.findContours(shapeMask.copy(), cv2.RETR_EXTERNAL,
cv2.CHAIN_APPROX_SIMPLE)
print ("I found %d black shapes" % (len(cnts)))
cv2.imshow("Mask", shapeMask)
# loop over the contours
for c in cnts:
# draw the contour and show it
cv2.drawContours(image, [c], -1, (0, 255, 0), 2)
cv2.imshow("Image", image)
cv2.waitKey(0)
Чтобы решить эту проблему. Вам нужно сделать следующее:
Вот код:
import cv2
import numpy as np
big_img = cv2.imread("color_img.jpg", 1)
monkey_img = cv2.imread("monkey.png", 1)
# define green value range
big_img_hsv = cv2.cvtColor(big_img, cv2.COLOR_BGR2HSV)
mask = cv2.inRange(big_img_hsv, (36, 0, 0), (70, 255,255))
# find the contours in the mask
img, contours, hierarchy = cv2.findContours(mask.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# find the contour with max area
cnt = sorted(contours, key=cv2.contourArea, reverse=True)[0]
# cv2.drawContours(big_img, [cnt], 0, (0,0,255), 3)
# Find the bounding box in that region
x,y,w,h = cv2.boundingRect(cnt)
rect = (x, y), (x + w, y + h)
#cv2.rectangle(big_img,(x,y),(x+w,y+h),(0,255,0),2)
# Put the monkey to that region
img_height, img_width = monkey_img.shape[:2]
# you like to put the monkey image to the center of this region
center_x = int(round(x + w / 2))
center_y = int(round(y + h / 2))
# so the starting point should be
start_x = int(round(center_x - img_width / 2))
start_y = int(round(center_y - img_height / 2))
mask_img = np.where(monkey_img==[0,0,0])
# Grap information from original image
crop_from_original = big_img[start_y: start_y + img_height, start_x: start_x+img_width ]
# put the pixel to monkey image
monkey_img[mask_img] = crop_from_original[mask_img]
# put the monkey to the right image
big_img[start_y:start_y+img_height,start_x: start_x+img_width]=monkey_img
cv2.imshow("big_img", big_img)
cv2.waitKey()