0
我在Python 2.7.6中遇到了一些麻煩,從字典中獲取信息並做一些有用的工作。我附上了我的整個代碼,因爲我不確定具體是什麼錯誤,這可能不是我期待的。Python 2.7.6字典
我想生成一些測試數據;一束隨機分佈的圖像源(1),從正確的位置移動一小部分。我使用字典分別跟蹤每個源,並使用包含偏移源的每個圖像在字典中使用字典。
我的問題是當我想要獲取圖像中源的平均運動。我相信這個問題很清楚(大約一半)。我已經嘗試了幾種不同的技術,他們被評論了。目前我只使用3張圖片,但我打算明顯增加這個數字。如果我堅持只有3個,我會用一種不同的方法去做,並且寫出很多這樣的東西。
我已經看過這樣的其他問題,但沒有發現任何特定於我的問題,這可能是因爲我不知道它是什麼,我正在嘗試做的行話。道歉,如果這已被問及以前解決。
# Source position-offset tracker
import math
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import copy
import random
from pylab import boxplot
#FUNCTIONS
def random_movement(source_positions):
source_positions_changed={}
for n in range(len(source_positions)): # n = [0,1]
key = source_positions.keys()[n]
del_x = source_positions[key][0]+random.randint(0,1)
del_y = source_positions[key][1]+random.randint(0,1)
source_positions_changed[key] = (del_x,del_y)
return source_positions_changed
#OTHER CODE
# put in original positions
# -> randomly distributed
# -> of values 0 or 1 only
original_positions = np.random.randint(2,size=(10,10))
# Tag each source within the image to keep track of them
source_positions = {}
source_count=0
for x in range(len(original_positions)):
for y in range(len(original_positions[0])):
if original_positions[x,y] == 1: # finding all sources
source_count += 1
index = 'S'+str(source_count)
source_positions[index] = (x,y)
# attach a source name to its position
source_numbers = len(source_positions)
number_timesteps = 2 # how many images were taken NOT including the original
# create a dictionary for the timesteps of shifted sources
# timesteps are the images where the sources have moves from the correct position
dictionary = {}
for x in range(1,number_timesteps+1):
#exec('dictionary%s = copy.copy(random_movement(source_positions))'%x)
dictionary['position_changed{0}'.format(x)] = copy.copy(random_movement(source_positions))
# finding the distances from the sources original positions
#source_distance_sum = {}
#################################################
### THIS IS WHERE I THINK I'M HAVING PROBLEMS ###
#################################################
# this should take make the motion of any sources that appear outside the range of the image -1
# and for sources that remain in range should find the motion from the correct position
# using equation: a^2 = b^2 + c^2
# should end up with source_distance_sum1 and source_distance_sum2 that have the motions from the correct positions of each source for the images, whose positional information was stored in dictionary['position_changed1'] and dictionary['position_changed2'] respectively
#source_distance_sum=[]
#distance_moved=[]
for source in range(1,source_numbers+1):
#source_distance_sum['S{0}'.format(source)]=0
for tstep in range(1,number_timesteps+1):
exec('source_distance_sum%s=[]'%tstep)
if dictionary['position_changed{0}'.format(tstep)]['S{0}'.format(source)][0]>=len(original_positions) or dictionary['position_changed{0}'.format(tstep)]['S{0}'.format(source)][1]>=len(original_positions[0]):
#if 'dictionary%s[S%s][0]>=len(original_positions) or dictionary%s[S%s][1]>=len(original_positions[0])'%(tstep,source,tstep,source)
#source_distance_sum['S{0}'.format(source)]=-1
exec('source_distance_sum%s.append(-1)'%tstep)
#print 'if 1: '+str(source_distance_sum1)
#print 'if 2: '+str(source_distance_sum2)
# dealing with sources moved out of range
else:
distance_moved=np.sqrt((source_positions['S{0}'.format(source)][0]-dictionary['position_changed{0}'.format(tstep)]['S{0}'.format(source)][0])**2+(source_positions['S{0}'.format(source)][1]-dictionary['position_changed{0}'.format(tstep)]['S{0}'.format(source)][1])**2)
# I have tried changing distance_moved as well, in similar ways to source_distance_sum, but I have as yet had no luck.
#source_distance_sum['S{0}'.format(source)]=distance_moved
exec('source_distance_sum%s.append(distance_moved)'%tstep)
# why does this not work!!!!????? I really feel like it should...
# for movement that stays in range
#print 'else 1: '+str(source_distance_sum1)
#print 'else 2: '+str(source_distance_sum2)
# then I want to use the information from the source_distance_sum1 & 2 and find the averages. I realise the following code will not work, but I cannot get the previous paragraph to work, so have not moved on to fixing the following.
# average distance:
source_distance = []
for source in range(1,len(source_distance_sum)+1):
if source_distance_sum['S{0}'.format(source)] > -1:
source_distance.append(source_distance_sum['S{0}'.format(source)])
average = sum(source_distance)/float(len(source_distance))
# set range of graph
#axx_max = np.ceil(max(distance_travelled))
#axy_max = np.ceil(max(number_of_sources))
# plot graph
fig = plt.figure()
#plt.axis([-1,axx_max+1,-1,axy_max+1])
plt.xlabel('Data set')
plt.ylabel('Average distance travelled')
plt.title('There are %s source(s) with %s valid' % (source_count,len(source_distance)))
ax1 = fig.add_subplot(111)
ax1.scatter(1, average, s=10, c='b', marker="+", label='First timestep')
#ax1.scatter(x[40:],y[40:], s=10, c='r', marker="o", label='second')
plt.legend(loc='upper left');
plt.show()
# NOTES AND REMOVED CODE
# Move sources around over time
# -> keep within a fixed range of motion
# -> randomly generate motion
# Calculate motion of sources from images
# -> ignore direction
# -> all that move by same magnitude get stored together
# -> Number of sources against magnitude of motion
# Make dictionary of number of sources that have moved a certain amount.
#source_motion_count = {} # make length of sources, values all 0
#for elem in range(len(source_distance)):
# if type(source_distance[elem])!=str and source_distance[elem]>-1:
# source_motion_count[source_distance[elem]] = 0
#for elem in range(len(source_distance)):
# if type(source_distance[elem])!=str and source_distance[elem]>-1:
# source_motion_count[source_distance[elem]] += 1
# Compile count of sources based on movement into graph
#number_of_sources = []
#distance_travelled = []
#for n in range(len(source_motion_count)):
# key=source_motion_count.keys()[n]
# number_of_sources.append(source_motion_count[key])
# distance_travelled.append(key)