2017-02-21 58 views
0

イメージに線を描いて、pt1をクリックしてpt2までドラッグする必要があります。その結果、行が表示され、pt1とpt2の座標も取得されます。私は現在、次のコードで線を描くために2回の別々のマウスクリックを使用しています。マウスをドラッグして線を描き、opencvで線の終点の座標を取得するPython

import numpy as np 
import cv2 

def get_points(im): 
    # Set up data to send to mouse handler 
    data = {} 
    data['im'] = im.copy() 
    data['points'] = [] 

    # Set the callback function for any mouse event 
    cv2.imshow("Image", im) 
    cv2.setMouseCallback("Image", mouse_handler, data) 
    cv2.waitKey(0) 

    # Convert array to np.array 
    points = np.vstack(data['points']).astype(float) 

    return points 

def mouse_handler(event, x, y, flags, data): 

    if event == cv2.EVENT_LBUTTONDOWN: 
     cv2.circle(data['im'], (x, y), 3, (0, 0, 255), 5, 16); 
     cv2.imshow("Image", data['im']); 
     if len(data['points']) < 2: # This can be changed for more or less points 
      data['points'].append([x, y]) 


# Running the code 
img = cv2.imread('image.jpg', 0) 
pts = get_points(img) 
cv2.line(img, (pts[0][0], pts[0][1]), (pts[1][0], pts[1][1]), (0,0,0), 2) 
cv2.imshow('Image', img) 
cv2.waitKey(0) 

これは機能しますが、私の問題は解決しません。私はそれをpt1からpt2にドラッグして、クリックを使ってポイントを取得してから線を引くのではなく、それを自分自身で描きたいと思います。例えば、下記の左の私の現在の実装上の画像が、私はそれをやりたいので、事前にご提案のために右の画像に

enter image description here

感謝を行ったように。

答えて

0

他のイベントも使用してください。ここで

は、迅速な汚いソリューションです:

import numpy as np 
import cv2 

btn_down = False 

def get_points(im): 
    # Set up data to send to mouse handler 
    data = {} 
    data['im'] = im.copy() 
    data['lines'] = [] 

    # Set the callback function for any mouse event 
    cv2.imshow("Image", im) 
    cv2.setMouseCallback("Image", mouse_handler, data) 
    cv2.waitKey(0) 

    # Convert array to np.array in shape n,2,2 
    points = np.uint16(data['lines']) 

    return points, data['im'] 

def mouse_handler(event, x, y, flags, data): 
    global btn_down 

    if event == cv2.EVENT_LBUTTONUP and btn_down: 
     #if you release the button, finish the line 
     btn_down = False 
     data['lines'][0].append((x, y)) #append the seconf point 
     cv2.circle(data['im'], (x, y), 3, (0, 0, 255),5) 
     cv2.line(data['im'], data['lines'][0][0], data['lines'][0][1], (0,0,255), 2) 
     cv2.imshow("Image", data['im']) 

    elif event == cv2.EVENT_MOUSEMOVE and btn_down: 
     #thi is just for a ine visualization 
     image = data['im'].copy() 
     cv2.line(image, data['lines'][0][0], (x, y), (0,0,0), 1) 
     cv2.imshow("Image", image) 

    elif event == cv2.EVENT_LBUTTONDOWN and len(data['lines']) < 2: 
     btn_down = True 
     data['lines'].insert(0,[(x, y)]) #prepend the point 
     cv2.circle(data['im'], (x, y), 3, (0, 0, 255), 5, 16) 
     cv2.imshow("Image", data['im']) 


# Running the code 
img = cv2.imread('C://image.jpg', 1) 
pts, final_image = get_points(img) 
cv2.imshow('Image', final_image) 
print pts 
cv2.waitKey(0) 

は、Th1は、あなたが考えていたものであるなら、私に教えてください。

関連する問題