2015-09-24 339 views
1

我希望在顯示圖像時通過右鍵單擊鼠標來收集像素位置(第i行,第列)。使用鼠標單擊/事件獲取像素位置

這大約是從互聯網上下載的圖片一個簡單的例子:

import urllib 
import cv2 
from win32api import GetSystemMetrics 

path_image = urllib.urlretrieve("http://www.bellazon.com/main/uploads/monthly_06_2013/post-37737-0-06086500-1371727837.jpg", "local-filename.jpg")[0] 
img = cv2.imread(path_image,0) 
width = GetSystemMetrics(0) 
height = GetSystemMetrics(1) 
scale_width = width/img.shape[1] 
scale_height = height/img.shape[0] 
scale = min(scale_width, scale_height) 
window_width = int(img.shape[1] * scale) 
window_height = int(img.shape[0] * scale) 
cv2.namedWindow('image', cv2.WINDOW_NORMAL) 
cv2.resizeWindow('image', window_width, window_height) 
cv2.imshow('image', img) 
cv2.waitKey(0) 
cv2.destroyAllWindows() 

在這一點上,我希望瞭解收集和儲存在list像素位置的最佳途徑。

回答

1
import urllib 
import cv2 
from win32api import GetSystemMetrics 

#the [x, y] for each right-click event will be stored here 
right_clicks = list() 

#this function will be called whenever the mouse is right-clicked 
def mouse_callback(event, x, y, flags, params): 

    #right-click event value is 2 
    if event == 2: 
     global right_clicks 

     #store the coordinates of the right-click event 
     right_clicks.append([x, y]) 

     #this just verifies that the mouse data is being collected 
     #you probably want to remove this later 
     print right_clicks 

path_image = urllib.urlretrieve("http://www.bellazon.com/main/uploads/monthly_06_2013/post-37737-0-06086500-1371727837.jpg", "local-filename.jpg")[0] 
img = cv2.imread(path_image,0) 
width = GetSystemMetrics(0) 
height = GetSystemMetrics(1) 
scale_width = 640/img.shape[1] 
scale_height = 480/img.shape[0] 
scale = min(scale_width, scale_height) 
window_width = int(img.shape[1] * scale) 
window_height = int(img.shape[0] * scale) 
cv2.namedWindow('image', cv2.WINDOW_NORMAL) 
cv2.resizeWindow('image', window_width, window_height) 

#set mouse callback function for window 
cv2.setMouseCallback('image', mouse_callback) 

cv2.imshow('image', img) 
cv2.waitKey(0) 
cv2.destroyAllWindows() 
相關問題