저는 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)