那個跳一跳python“外掛”,有幾個python文件,其中有一個是得到截圖,然后鼠標在圖片上點擊兩次,python窗口上會打印兩次鼠標的位置,并且會跟上一行這兩個點之間的距離。
這個功能我先給除去獲取截屏,就說怎么在某張圖片上算出兩次點擊的距離。
首先,需要用到圖形模塊,PIL:
1
2
|
from PIL import Image img = Image. open ( '0.jpg' ) |
然后用圖形繪制模塊matplotlib來給出一個plot對象:
1
2
|
import matplotlib.pyplot as plt fig = plt.figure() |
給這個對象加上剛剛打開圖片的標簽:
1
|
plt.imshow(img, animated = True ) |
然后用matplotlib的canvas.mpl_connect函數,將我們點擊的動作和圖片連接起來,這個函數的第二個參數要我們自己的寫。
1
|
fig.canvas.mpl_connect( 'button_press_event' , on_press) |
在這個自定義的on_press函數,我們要實現得到兩個點以后再算出距離。
那么我們就要有變量來儲存兩個點,臨時儲存點,來計算點擊了多少次,橫縱坐標
分別用全局變量cor=[0,0],coords=[], click_count=0,ix,iy
1
2
3
4
5
6
7
8
9
10
|
global ix,iy global click_count global cor ix,iy = event.xdata, event.ydata coords = [] coords.append((ix,iy)) print ( "now = " , coords) cor.append(coords) click_count + = 1 |
先把點儲存在臨時的coords里面,打印出當前位置,然后將臨時的放入全局變量cor里面, 并且點擊次數+1.
1
2
3
4
5
6
7
8
9
|
if click_count > 1 : click_count = 0 cor1 = cor.pop() cor2 = cor.pop() distance = (cor1[ 0 ][ 0 ] - cor2[ 0 ][ 0 ]) * * 2 + (cor1[ 0 ][ 1 ] - cor2[ 0 ][ 1 ]) * * 2 distance = distance * * 0.5 print ( "distance = " , distance) |
當點擊次數大于1的時候,就說明已經儲存了兩個點了。
這里用的棧pop()方法得到兩個點,分別放入cor1 和 cor2, 那么cor1 和 cor2 就是兩個點了。
接著計算出距離distance就行了。
完整代碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
|
import numpy as np from matplotlib.animation import FuncAnimation import matplotlib.pyplot as plt from PIL import Image def on_press(event): global ix,iy global click_count global cor ix,iy = event.xdata, event.ydata coords = [] coords.append((ix,iy)) print ( "now = " , coords) cor.append(coords) click_count + = 1 if click_count > 1 : click_count = 0 cor1 = cor.pop() cor2 = cor.pop() distance = (cor1[ 0 ][ 0 ] - cor2[ 0 ][ 0 ]) * * 2 + (cor1[ 0 ][ 1 ] - cor2[ 0 ][ 1 ]) * * 2 distance = distance * * 0.5 print ( "distance = " , distance) cor = [ 0 , 0 ] click_count = 0 fig = plt.figure() img = Image. open ( '0.jpg' ) #updata = True plt.imshow(img, animated = True ) fig.canvas.mpl_connect( 'button_press_event' , on_press) plt.show() |
最終效果:
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:http://blog.csdn.net/Big_Head_/article/details/78976302