2017-09-07 46 views
0

我有輪廓的位置,我怎樣才能將圖像或視頻放在輪廓的相同位置,另一方面因爲我可以減小兩者的大小。 我的代碼是如何將圖像或視頻放在輪廓線的相同位置python + opencv

import cv2 
import numpy as np 

#Iniciar camara 
captura = cv2.VideoCapture(0) 

while(1): 

#Caputrar una imagen y convertirla a hsv 
_, imagen = captura.read() 
hsv = cv2.cvtColor(imagen, cv2.COLOR_BGR2HSV) 
img=cv2.imread('calibresult.png') 
#Guardamos el rango de colores hsv (azules) 
bajos = np.array([100,65,75], dtype=np.uint8) 
altos = np.array([130, 255, 255], dtype=np.uint8) 

#Crear una mascara que detecte los colores 
mask = cv2.inRange(hsv, bajos, altos) 

#Filtrar el ruido con un CLOSE seguido de un OPEN 
kernel = np.ones((6,6),np.uint8) 
mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel) 
mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel) 

#Difuminamos la mascara para suavizar los contornos y aplicamos filtro canny 
blur = cv2.GaussianBlur(mask, (5, 5), 0) 
edges = cv2.Canny(mask,1,2) 

#Si el area blanca de la mascara es superior a 500px, no se trata de ruido 
contours, hier = cv2.findContours(edges,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) 
areas = [cv2.contourArea(c) for c in contours] 
i = 0 
for extension in areas: 
    if extension > 600: 
     actual = contours[i]#position of countour 
     approx = cv2.approxPolyDP(actual,0.05*cv2.arcLength(actual,True),True) 
     if len(approx)==3: 
      cv2.drawContours(imagen,[actual],0,(0,0,255),2) 
      cv2.drawContours(mask,[actual],0,(0,0,255),2) 

     i = i+1 

cv2.imshow('mask', mask) 
cv2.imshow('Camara', imagen) 
tecla = cv2.waitKey(5) & 0xFF 
if tecla == 27: 
    break 

cv2.destroyAllWindows() 

「實際」的輪廓 例如,我想要的代碼註冊一個矩形的圖像,並在大綱的地方的同一位置的輪廓的位置,一切都是實時時間,位置將是相對於所述輪廓

+0

我仍然不明白你的意思是「我怎麼能把圖像或視頻放在輪廓的相同位置」。你能進一步澄清這一點嗎?你有你想要的輸出的視覺表示? – eshirima

+0

例如,我想代碼註冊一個矩形的輪廓,並在輪廓的相同位置放置一個圖像,所有實時,位置將相對於輪廓的中心 –

回答

0

的中心從優異的答案給出here

dst = cv2.imread("destination.jpg", -1) 
src = cv2.imread("source.jpg", -1) 

gray = cv2.cvtColor(dst, cv2.COLOR_BGR2GRAY) 
ret, binary = cv2.threshold(gray, 130, 255, cv2.THRESH_BINARY) 

im2,contours,hierarchy = cv2.findContours(binary, cv2.RETR_LIST, cv2.CHAIN_APPROX_NONE) 

for contour in contours: 
    cv2.drawContours(dst, contour, -1, (0,0,255), thickness = 2) 

locs = np.where(binary != 0) # Get the non-zero mask locations 

# Case #1 - Other image is grayscale and source image is colour 
if len(dst.shape) == 3 and len(src.shape) != 3: 
    dst[locs[0], locs[1]] = src[locs[0], locs[1], None] 
# Case #2 - Both images are colour or grayscale 
elif (len(dst.shape) == 3 and len(src.shape) == 3) or (len(dst.shape) == 1 and len(src.shape) == 1): 
    dst[locs[0], locs[1]] = src[locs[0], locs[1]] 
# Otherwise, we can't do this 
else: 
    raise Exception("Incompatible input and output dimensions") 

enter image description here

+0

非常感謝你會幫助我很多 –