如何在图像中找到所有颜色形状打开CV Python

时间:2018-07-31 10:08:47

标签: python numpy opencv

我有此图像,需要在图像中查找彩色形状 enter image description here

我需要这些彩色形状的位置。

我需要把这只猴子放在绿色三角形上

enter image description here

我的代码给我错误 该代码只能检测黑色,但会引发错误。

{  "code" : 403,  "errors" : [ {    "domain" : "global",
"message" : "User does not have sufficient permission for site 'https://abc.xyz.com'. See also: https://support.google.com/webmasters/answer/2451999.",
"reason" : "forbidden"  } ],  "message" : "User does not have sufficient permission for site 'https://abc.xyz.com'. See also: https://support.google.com/webmasters/answer/2451999."}

1 个答案:

答案 0 :(得分:1)

enter image description here

为了解决这个问题。您需要执行以下操作:

  1. 在HSV空间中找到绿色的正确区域
  2. 使用轮廓检测​​找到可能的区域
  3. 按区域大小对候选人进行排序
  4. 找到最大尺寸的那个区域的边界框
  5. 计算边界框的中心
  6. 修复猴子图像的背景。
  7. 将猴子图像放置在正确的位置。

这是代码:

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()