some files

This commit is contained in:
Jan Grewe 2021-01-21 08:36:35 +01:00
parent 768ae7f0b6
commit 071f9e1d21
4 changed files with 241 additions and 0 deletions

120
boldness_darkside.py Normal file
View File

@ -0,0 +1,120 @@
import numpy as np
import matplotlib.pyplot as plt
import image_marker as im
import tracking_result as tr
import os
import glob
import argparse
from IPython import embed
#1. Tankkoordinaten
def tankcoordinates(video, dontask=False):
redo = True
if os.path.exists('tankcoordinates.py'):
from tankcoordinates import bottom_left, bottom_right, top_left, top_right
print("Found tank coordinates top left: %s, top right: %s" % (top_left, top_right))
if dontask:
return bottom_left, top_left, top_right, bottom_right
answer = input('Redo markers? y/n')
if answer == 'y' or answer == 'Y':
redo = True
else:
redo = False
if redo:
tank_task = im.MarkerTask("tank limits", ["bottom left corner", "top left corner", "top right corner", "bottom right corner"], "Mark tank corners")
image_marker = im.ImageMarker([tank_task])
marker_positions = image_marker.mark_movie(video, 100)
bottom_right = marker_positions[0]['bottom right corner']
bottom_left = marker_positions[0]['bottom left corner']
top_right = marker_positions[0]['top right corner']
top_left = marker_positions[0]['top left corner']
with open('tankcoordinates.py', 'w') as f:
f.write('bottom_left = %s\n' % str(marker_positions[0]['bottom left corner']))
f.write('top_left = %s\n' % str(marker_positions[0]['top left corner']))
f.write('top_right = %s\n' % str(marker_positions[0]['top right corner']))
f.write('bottom_right = %s\n' % str(marker_positions[0]['bottom right corner']))
return bottom_left, top_left, top_right, bottom_right
#2. Feederkoordinaten
#3. dark_light Koordinaten
def dark_light_coordinates(video, dontask=False):
redo = True
if os.path.exists('dark_light_coordinates.py'):
from dark_light_coordinates import left, right, dark_center
print("Found dark_light_coordinates left: %s, right: %s, dark_center: %s" % (left, right, dark_center))
if dontask:
return left, right, dark_center
answer = input('Redo markers? y/n')
if answer == 'y' or answer == 'Y':
redo = True
else:
redo = False
if redo:
dark_light_task = im.MarkerTask('Dark side', ['left', 'right', 'dark_center'], 'Mark light dark separator line')
image_marker = im.ImageMarker([dark_light_task])
marker_positions = image_marker.mark_movie(video, 100)
right = tr.coordinate_transformation(marker_positions[0]['right'])
left = tr.coordinate_transformation(marker_positions[0]['left'])
dark_center = tr.coordinate_transformation(marker_positions[0]['dark_center'])
with open('dark_light_coordinates.py', 'w') as f:
f.write('left = %s\n' % str(left))
f.write('right = %s\n' % str(right))
f.write('dark_center = %s\n' % str(dark_center))
return left, right, dark_center
#4. Laden der Trackingresults
def load_tracking_results(dlc_results_file):
trs = tr.TrackingResult(dlc_results_file)
t, x, y, l, name = trs.position_values(bodypart="snout", framerate=30)
return t, x, y, l
#5. Wie lange hält sich der Fisch im Hellen/Dunklen auf?
# Anzahl Frames in der Fisch in definiertem, dunklen Bereich ist, bzw. in der der Fisch nicht im Hellen ist
def aufenthaltsort(left, center, fish_y):
top_is_dark=left[1]>=center[1]
#bei wie vielen Frames ist der Fisch im Hellen?
if top_is_dark:
hell_count = len(fish_y[fish_y >= left[1]])
else:
hell_count = len(fish_y[fish_y < left[1]])
dark_count=len(fish_y) - hell_count
total_count = len(fish_y)
return hell_count, dark_count, total_count
def analysiere_video(v, dlc, left, center):
t, fish_x, fish_y, likelihood = load_tracking_results(dlc)
hc, dc, tc = aufenthaltsort(left, center, fish_y)
print('Der Fisch hat sich %.2f %% im Dunklen aufgehalten.'%(dc/tc*100))
return (dc/tc*100)
def main():
parser = argparse.ArgumentParser(description="")
parser.add_argument("day", type=str, help="The day you want to work on")
parser.add_argument("-f", "--folder", type=str, default="/data/boldness/labeled_videos", help="The base folder in which the labeled videos are stored. Default is /data/boldness/labeled_videos")
parser.add_argument("-a", "--animal", type=str, default="*", help="The animal id, default is * for all animals")
parser.add_argument("-e", "--extension", type=str, default=".mp4", help="The video file extension, default is .mp4")
parser.add_argument("-na", "--noask", action="store_true", help="do not ask for coordinates")
args = parser.parse_args()
videos = sorted(glob.glob(os.path.join(args.folder, args.day, '*%s*%s' % (args.animal, args.extension))))
dlc_files = sorted(glob.glob(os.path.join(args.folder, args.day, '*%s*%s' % (args.animal, '.h5'))))
results = {}
if len(videos) > 0:
left, right, center = dark_light_coordinates(videos[0], args.noask)
# bl, tl, tr, br = tankcoordinates(v, args.noask)
for video, dlc_file in zip(videos, dlc_files):
animal = video.split(os.sep)[-1].split('_')[1]
p_dark = analysiere_video(video, dlc_file, left, center)
results[animal] = p_dark
np.save('results_%s.npy' % args.day, results)
print(results)
if __name__ == '__main__':
main()

29
dark_light_preference.py Normal file
View File

@ -0,0 +1,29 @@
import numpy as np
import os
import glob
import matplotlib.pyplot as pyplot
from IPython import embed
if __name__ == "__main__":
result_files = sorted(glob.glob("./results_day*.npy"))
results = {}
for r in result_files:
day = r.split(os.sep)[-1].split('_')[-1].split('.')[0]
if "day" in results.keys():
results["day"].append(day)
else:
results["day"] = [day]
data = np.load(r, allow_pickle=True)
d = data.item()
for k in d.keys():
if k in results.keys():
results[k].append(d[k])
else:
results[k] =[d[k]]
#res= dict((k, results[k]) for k in ['lepto03DLC' , 'lepto48DLC'] if k in results)
#print(res)
print(results)

64
feeder_positions.py Normal file
View File

@ -0,0 +1,64 @@
import image_marker as im
import matplotlib.pyplot as plt
import numpy as np
import tracking_result as tr
from IPython import embed
import argparse
import glob
import sys
import dark_light_coordinates as dl
x_limits = np.array([0, 124])
y_limits = np.array([0, 81])
light_area_y = [45.5, 81]
def get_risk(position, light_area_y, light_risk_scale=3, x_limits=np.array([0, 124]), y_limits = np.array([0, 81])):
"""Calculates the risk associated with a certain position in the arena
Args:
position (iterable): two-element vector of position i.e. (x,y)
light_area_y (iterable): two element vactor with the start and stop y-coordinates of light area
light_risk_scale (int, optional): if position is on th birght side, risk is scaled by this number. Defaults to 2.
x_limits : extent of the tank on x axis in cm
y_limits : extent of the tank on y axis in cm
Returns:
float: the risk for this position
"""
min_wall_dist_x = min(np.abs(position[0] - x_limits))
min_wall_dist_y = min(np.abs(position[1] - y_limits))
risk_x = 1/(max(x_limits)/2) * min_wall_dist_x
risk_y = 1/(max(y_limits)/2) * min_wall_dist_y
#risk_y = 1/(np.abs(np.diff(light_area_y))/2) * min_wall_dist_y
total_risk = min(risk_x,risk_y) #+ 0.25 * (risk_x + risk_y)
is_position_on_the_bright_side = position[1] >= light_area_y[0] and position[1] < light_area_y[1]
if is_position_on_the_bright_side:
total_risk = total_risk + 1
return total_risk
x_positions = np.arange(0,125, 5)
y_positions = np.arange(0, 81, 5)
risk_matrix = np.zeros((len(x_positions), len(y_positions)))
print(risk_matrix.shape)
for i, x in enumerate(x_positions):
for j, y in enumerate(y_positions):
risk_matrix[i, j] = get_risk([x, y], light_area_y)
plt.imshow(risk_matrix)
plt.show()
"""
if __name__ == '__main__':
vid = '/mnt/movies/merle_verena/boldness/labeled_videos/day_5/2020.12.07_lepto48.m4v'
feeder_task = im.MarkerTask("Feeder positions", list(map(str, range(1, 9))), "Mark feeder positions")
tasks = [feeder_task]
image_marker = im.ImageMarker(tasks)
# vid1 = "2020.12.11_lepto48DLC_resnet50_boldnessDec11shuffle1_200000_labeled.mp4"
print(sys.argv[0])
print (sys.argv[1])
vid1 = sys.argv[1]
marker_positions = im.mark_movie(vid1, 10)
print(marker_positions)
"""

28
speed.py Normal file
View File

@ -0,0 +1,28 @@
import sys
import tracking_result as tr
import numpy as np
import matplotlib.pyplot as plt
from IPython import embed
#tracking_tools]$ python3 speed.py /mnt/movies/merle_verena/boldness/labeled_videos/day_1/2020.12.01_lepto03DLC_resnet50_boldnessDec11shuffle1_200000.h5
if __name__ == '__main__' :
dlc_results = sys.argv[1]
trs = tr.TrackingResult(dlc_results)
t, x, y, l, name = trs.position_values(bodypart="snout", framerate=30)
t = t[l > 0.975]
x = x[l > 0.975]
y = y[l > 0.975]
# Dann Differenzen berechnen
dx= np.diff(x)
dy= np.diff(y)
dt= np.diff(t)
s = np.sqrt(dx**2 + dy**2)
v = s/dt
embed ()
plt.scatter(x[:-1],y[:-1],c=v)
plt.show()