Static Colormap in Scatter Plot during Addition of Datapoints - python-3.x

I would like to add the datapoints to a locked portion of the screen one after the other, save all plots as a *.png and make a gif. Everything is working so far, but I want to lock the colorbar, so that it does not change its range during the addition of the points. I have no idea on how to do tackle this problem...
The input data is (the t_string will be modified to make it work):
x = [2.803480599999999, 5.5502475000000056, 6.984381300000002, 4.115224099999998, 5.746583699999995, 8.971469500000019, 12.028179500000032, 13.451193300000014, 12.457393999999972, 12.027555199999998, 16.077930800000015, 5.021229700000006, 11.206380399999999, 7.903262600000004, 11.98195070000001, 12.21701, 10.35045, 10.231890000000002]
y = [11.961321698938578, 5.218986480632915, 5.211628408660906, 4.847852635777481, 4.936266162218553, 5.233256380128127, 5.441388698929861, 5.461721129728066, 5.722170570613203, 5.2698434785261545, 5.645419662253215, 4.617062894639794, 4.973357261130752, 5.906843248930297, 5.256517482861392, 5.537361432952908, 5.339542403148332, 5.376979880224148]
t_string = ['2019-10-7', '2019-10-13', '2019-11-10', '2019-11-16', '2019-11-17', '2019-11-23', '2019-11-24', '2019-11-27', '2019-12-1', '2019-12-4', '2019-12-8', '2019-12-21', '2019-12-23', '2019-12-25', '2019-12-27', '2020-1-2', '2020-1-5', '2020-1-9']
Below you find the whole code I used. It will create a new directory in your working directory and write all files in there, you will also find the .gif in there. It might be necessary to install some packages. Many thanks in ad
# Import some stuff
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from datetime import datetime
import pathlib
from pathlib import Path
import moviepy.editor as mpy
# Define Input
x = [2.803480599999999, 5.5502475000000056, 6.984381300000002, 4.115224099999998, 5.746583699999995, 8.971469500000019,
12.028179500000032, 13.451193300000014, 12.457393999999972, 12.027555199999998, 16.077930800000015,
5.021229700000006, 11.206380399999999, 7.903262600000004, 11.98195070000001, 12.21701, 10.35045,
10.231890000000002]
y = [11.961321698938578, 5.218986480632915, 5.211628408660906, 4.847852635777481, 4.936266162218553, 5.233256380128127,
5.441388698929861, 5.461721129728066, 5.722170570613203, 5.2698434785261545, 5.645419662253215, 4.617062894639794,
4.973357261130752, 5.906843248930297, 5.256517482861392, 5.537361432952908, 5.339542403148332, 5.376979880224148]
t_string = ['2019-10-7', '2019-10-13', '2019-11-10', '2019-11-16', '2019-11-17', '2019-11-23', '2019-11-24',
'2019-11-27', '2019-12-1', '2019-12-4', '2019-12-8', '2019-12-21', '2019-12-23', '2019-12-25', '2019-12-27',
'2020-1-2', '2020-1-5', '2020-1-9']
# Define a function to get the datafiles with a certain suffix in a path
def getfile_UI(file_directory, file_suffix):
from glob import glob
path_to_search = file_directory / file_suffix
filenames = glob(str(path_to_search))
return filenames
# Start of script/calculations
t = [mdates.date2num(datetime.strptime(i, "%Y-%m-%d")) for i in t_string]
workingdirectory_projectfolder = Path.cwd().parent
my_dpi = 75
for index, entry in enumerate(t_string):
fig = plt.figure(figsize=(480 / my_dpi, 480 / my_dpi), dpi=my_dpi)
sc = plt.scatter(x[0:index + 1],
y[0:index + 1],
c=t[0:index + 1])
plt.xlim(0, 20)
plt.ylim(4, 7)
plt.title(entry)
plt.xlabel("Distace [km]")
plt.ylabel("Pace [min/km]")
loc = mdates.AutoDateLocator()
fig.colorbar(sc, ticks=loc,
format=mdates.AutoDateFormatter(loc))
filename = 'png_' + str(index) + '.png'
new_dir = workingdirectory_projectfolder / "type 3 gif"
pathlib.Path(new_dir).mkdir(exist_ok=True)
plt.savefig(workingdirectory_projectfolder / "type 3 gif" / filename, dpi=96)
plt.gca()
# Make a GIF from all png files
# http://superfluoussextant.com/making-gifs-with-python.html
fps = 10
gif_name = str(fps) + " fps_""type3_"
workingdirectory_projectfolder = Path.cwd().parent
gif_path = workingdirectory_projectfolder / "type 3 gif" / gif_name
filenamelist_path = workingdirectory_projectfolder / "type 3 gif"
filenamelist_png = getfile_UI(filenamelist_path, "*.png")
list.sort(filenamelist_png, key=lambda x: int(
x.split('_')[1].split('.png')[0])) # Sort the images by #, this may need to be tweaked for your use case
clip = mpy.ImageSequenceClip(filenamelist_png, fps=fps)
clip.write_gif('{}.gif'.format(gif_path), fps=fps)

You could call plt.scatter with vmin=min(t), vmax=max(t). This fixes the limits used for coloring.
Something else you could add in your animation is to only show the tick dates up to the current:
loc = mdates.AutoDateLocator()
cbar = fig.colorbar(sc, ticks=loc, format=mdates.AutoDateFormatter(loc))
ticks = [ti for ti in cbar.get_ticks() if ti <= t[index]]
cbar.set_ticks(ticks)

Related

How can I interpolate values from two lists (in Python)?

I am relatively new to coding in Python. I have mainly used MatLab in the past and am used to having vectors that can be referenced explicitly rather than appended lists. I have a script where I generate a list of x- and y- (z-, v-, etc) values. Later, I want to interpolate and then print a table of the values at specified points. Here is a MWE. The problem is at line 48:
yq = interp1d(x_list, y_list, xq(nn))#interp1(output1(:,1),output1(:,2),xq(nn))
I'm not sure I have the correct syntax for the last two lines either:
table[nn] = ('%.2f' %xq, '%.2f' %yq)
print(table)
Here is the full script for the MWE:
#This script was written to test how to interpolate after data was created in a loop and stored as a list. Can a list be accessed explicitly like a vector in matlab?
#
from scipy.interpolate import interp1d
from math import * #for ceil
from astropy.table import Table #for Table
import numpy as np
# define the initial conditions
x = 0 # initial x position
y = 0 # initial y position
Rmax = 10 # maxium range
""" initializing variables for plots"""
x_list = [x]
y_list = [y]
""" define functions"""
# not necessary for this MWE
"""create sample data for MWE"""
# x and y data are calculated using functions and appended to their respective lists
h = 1
t = 0
tf = 10
N=ceil(tf/h)
# Example of interpolation without a loop: https://docs.scipy.org/doc/scipy/tutorial/interpolate.html#d-interpolation-interp1d
#x = np.linspace(0, 10, num=11, endpoint=True)
#y = np.cos(-x**2/9.0)
#f = interp1d(x, y)
for i in range(N):
x = h*i
y = cos(-x**2/9.0)
""" appends selected data for ability to plot"""
x_list.append(x)
y_list.append(y)
## Interpolation after x- and y-lists are already created
intervals = 0.5
nfinal = ceil(Rmax/intervals)
NN = nfinal+1 # length of table
dtype = [('Range (units?)', 'f8'), ('Drop? (units)', 'f8')]
table = Table(data=np.zeros(N, dtype=dtype))
for nn in range(NN):#for nn = 1:NN
xq = 0.0 + (nn-1)*intervals #0.0 + (nn-1)*intervals
yq = interp1d(x_list, y_list, xq(nn))#interp1(output1(:,1),output1(:,2),xq(nn))
table[nn] = ('%.2f' %xq, '%.2f' %yq)
print(table)
Your help and patience will be greatly appreciated!
Best regards,
Alex
Your code has some glaring issues that made it really difficult to understand. Let's first take a look at some things I needed to fix:
for i in range(N):
x = h*1
y = cos(-x**2/9.0)
""" appends selected data for ability to plot"""
x_list.append(x)
y_list.append(y)
You are appending a single value without modifying it. What I presume you wanted is down below.
intervals = 0.5
nfinal = ceil(Rmax/intervals)
NN = nfinal+1 # length of table
dtype = [('Range (units?)', 'f8'), ('Drop? (units)', 'f8')]
table = Table(data=np.zeros(N, dtype=dtype))
for nn in range(NN):#for nn = 1:NN
xq = 0.0 + (nn-1)*intervals #0.0 + (nn-1)*intervals
yq = interp1d(x_list, y_list, xq(nn))#interp1(output1(:,1),output1(:,2),xq(nn))
table[nn] = ('%.2f' %xq, '%.2f' %yq)
This is where things get strange. First: use pandas tables, this is the more popular choice. Second: I have no idea what you are trying to loop over. What I presume you wanted was to vary the number of points for the interpolation, which I have done so below. Third: you are trying to interpolate a point, when you probably want to interpolate over a range of points (...interpolation). Lastly, you are using the interp1d function incorrectly. Please take a look at the code below or run it here; let me know what you exactly wanted (specifically: what should xq / xq(nn) be?), because the MRE you provided is quite confusing.
from scipy.interpolate import interp1d
from math import *
import numpy as np
Rmax = 10
h = 1
t = 0
tf = 10
N = ceil(tf/h)
x = np.arange(0,N+1)
y = np.cos(-x**2/9.0)
interval = 0.5
NN = ceil(Rmax/interval) + 1
ip_list = np.arange(1,interval*NN,interval)
xtable = []
ytable = []
for i,nn in enumerate(ip_list):
f = interp1d(x,y)
x_i = np.arange(0,nn+interval,interval)
xtable += [x_i]
ytable += [f(x_i)]
[print(i) for i in xtable]
[print(i) for i in ytable]

Find the pixel_maxima in the image and also find its coordinates as well as the peak intensity

I have this input image and I wan to find pixel maxima and it should look like image2.
I tried contouring but its not working.I also tried scipy pixel_maxima it doesn't gives me result as image2.
here is the code, I have refered this answer (Get coordinates of local maxima in 2D array above certain value)
import numpy as np
import scipy.misc
import scipy.ndimage as ndimage
import scipy.ndimage.filters as filters
import matplotlib.pyplot as plt
import imageio
from skimage.color import rgb2gray
fname = 'slice-0001-trim.jpg'
neighborhood_size = 10
threshold = 12
data = imageio.imread(fname,as_gray=True)
data_max = filters.maximum_filter(data, neighborhood_size)
maxima = (data == data_max)
data_min = filters.minimum_filter(data, neighborhood_size)
diff = ((data_max - data_min) > threshold)
maxima[diff == 0] = 0
labeled, num_objects = ndimage.label(maxima)
slices = ndimage.find_objects(labeled)
x, y = [], []
for dy,dx in slices:
x_center = (dx.start + dx.stop - 1)/2
x.append(x_center)
y_center = (dy.start + dy.stop - 1)/2
y.append(y_center)
plt.imshow(data)
plt.savefig('sample.jpg', bbox_inches = 'tight')
plt.autoscale(False)
plt.plot(x,y, 'ro')
plt.savefig('result.png', bbox_inches = 'tight')
I need this image as result
But, I get this image as output

How to generate heat map on the Whole Slide Images (.svs format) using some probability values?

I am trying to generate heat map, or probability map, for Whole Slide Images (WSIs) using probability values. I have coordinate points (which determine areas on the WSIs) and corresponding probability values.
Basic Introduction on WSI: WSIs are large is size (almost 100000 x 100000 pixels). Hence, can't open these images using normal image viewer. The WSIs are processed using OpenSlide software.
I have seen previous posts in Stack Overflow on related to heat map, but as WSIs are processed in a different way, I am unable to figure out how to apply these solutions. Some examples that I followed: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, etc.
To generate heat map on WSIs, follow below instructions:
First of all Extract image patches and save the coordinates. Use below code for patch extraction. The code require some changes as per the requirements. The code has been copied from: patch extraction code link
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import logging
try:
import Image
except:
from PIL import Image
import math
import numpy as np
import openslide
import os
from time import strftime,gmtime
parser = argparse.ArgumentParser(description='Extract a series of patches from a whole slide image')
parser.add_argument("-i", "--image", dest='wsi', nargs='+', required=True, help="path to a whole slide image")
parser.add_argument("-p", "--patch_size", dest='patch_size', default=299, type=int, help="pixel width and height for patches")
parser.add_argument("-b", "--grey_limit", dest='grey_limit', default=0.8, type=float, help="greyscale value to determine if there is sufficient tissue present [default: `0.8`]")
parser.add_argument("-o", "--output", dest='output_name', default="output", help="Name of the output file directory [default: `output/`]")
parser.add_argument("-v", "--verbose",
dest="logLevel",
choices=['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'],
default="INFO",
help="Set the logging level")
args = parser.parse_args()
if args.logLevel:
logging.basicConfig(level=getattr(logging, args.logLevel))
wsi=' '.join(args.wsi)
""" Set global variables """
mean_grey_values = args.grey_limit * 255
number_of_useful_regions = 0
wsi=os.path.abspath(wsi)
outname=os.path.abspath(args.output_name)
basename = os.path.basename(wsi)
level = 0
def main():
img,num_x_patches,num_y_patches = open_slide()
logging.debug('img: {}, num_x_patches = {}, num_y_patches: {}'.format(img,num_x_patches,num_y_patches))
for x in range(num_x_patches):
for y in range(num_y_patches):
img_data = img.read_region((x*args.patch_size,y*args.patch_size),level, (args.patch_size, args.patch_size))
print_pics(x*args.patch_size,y*args.patch_size,img_data,img)
pc_uninformative = number_of_useful_regions/(num_x_patches*num_y_patches)*100
pc_uninformative = round(pc_uninformative,2)
logging.info('Completed patch extraction of {} images.'.format(number_of_useful_regions))
logging.info('{}% of the image is uninformative\n'.format(pc_uninformative))
def print_pics(x_top_left,y_top_left,img_data,img):
if x_top_left % 100 == 0 and y_top_left % 100 == 0 and x_top_left != 0:
pc_complete = round(x_top_left /img.level_dimensions[0][0],2) * 100
logging.info('{:.2f}% Complete at {}'.format(pc_complete,strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime())))
exit()
img_data_np = np.array(img_data)
""" Convert to grayscale"""
grey_img = rgb2gray(img_data_np)
if np.mean(grey_img) < mean_grey_values:
logging.debug('Image grayscale = {} compared to threshold {}'.format(np.mean(grey_img),mean_grey_values))
global number_of_useful_regions
number_of_useful_regions += 1
wsi_base = os.path.basename(wsi)
wsi_base = wsi_base.split('.')[0]
img_name = wsi_base + "_" + str(x_top_left) + "_" + str(y_top_left) + "_" + str(args.patch_size)
#write_img_rotations(img_data_np,img_name)
logging.debug('Saving {} {} {}'.format(x_top_left,y_top_left,np.mean(grey_img)))
save_image(img_data_np,1,img_name)
def gen_x_and_y(xlist,ylist,img):
for x in xlist:
for y in ylist:
img_data = img.read_region((x*args.patch_size,y*args.patch_size),level, (args.patch_size, args.patch_size))
yield (x, y,img_data)
def open_slide():
"""
The first level is always the main image
Get width and height tuple for the first level
"""
logging.debug('img: {}'.format(wsi))
img = openslide.OpenSlide(wsi)
img_dim = img.level_dimensions[0]
"""
Determine what the patch size should be, and how many iterations it will take to get through the WSI
"""
num_x_patches = int(math.floor(img_dim[0] / args.patch_size))
num_y_patches = int(math.floor(img_dim[1] / args.patch_size))
remainder_x = img_dim[0] % num_x_patches
remainder_y = img_dim[1] % num_y_patches
logging.debug('The WSI shape is {}'.format(img_dim))
logging.debug('There are {} x-patches and {} y-patches to iterate through'.format(num_x_patches,num_y_patches))
return img,num_x_patches,num_y_patches
def validate_dir_exists():
if os.path.isdir(outname) == False:
os.mkdir(outname)
logging.debug('Validated {} directory exists'.format(outname))
if os.path.exists(wsi):
logging.debug('Found the file {}'.format(wsi))
else:
logging.debug('Could not find the file {}'.format(wsi))
exit()
def rgb2gray(rgb):
"""Converts an RGB image into grayscale """
r, g, b = rgb[:,:,0], rgb[:,:,1], rgb[:,:,2]
gray = 0.2989 * r + 0.5870 * g + 0.1140 * b
return gray
def save_image(img,j,img_name):
tmp = os.path.join(outname,img_name+"_"+str(j)+".png")
try:
im = Image.fromarray(img)
im.save(tmp)
except:
print('Could not print {}'.format(tmp))
exit()
if __name__ == '__main__':
validate_dir_exists()
main()
Secondly, generate the probability values of each patches.
Finally, replace all the pixel values within a coordinates with the corresponding probability values and display the results using color maps.
This is the basic idea of generating heat map on WSIs. You can modify the code and concept to get a heat map as per your wish.
We have developed a python package for processing whole-slide-images:
https://github.com/amirakbarnejad/PyDmed
Here is a tutorial for getting heatmaps for whole-slide-images:
https://amirakbarnejad.github.io/Tutorial/tutorial_section5.html.
Also here is a sample notebook that gets heatmaps for WSIs using PyDmed:
Link to the sample notebook.
The benefit of PyDmed is that it is multi-processed. The dataloader sends a stream of patches to GPU(s), and the StreamWriter writes to disk in a separate process. Therefore, it is highly efficient. The running time of course depends on the machine, the size of WSIs, etc. On a good machine with a good GPU, PyDmed can generate heatmaps for ~120 WSIs in one day.

Estimating parameters using minimization in Python and speed up this process

I am trying to find parameter estimates using using minimization. The code I wrote works but there are two problems:
I finds only a local minimum. I tried to solve this by using basinhopping.
It takes very long until I get a result and since I have to do this minimization around 1000 times this becomes a big issue.
So my questions are:
Do you know how I could optimize my code so that it runs faster for the minimization.
Is there a way I can change the basinhopping part so that it runs faster? eg. set niter lower or a differnt method im not aware of. I tried running it like this and after 10 hour I didnt get a response for even one of the 1000 individuals for basinhopping.
Is there another way to find a global minimum?
Feel free to ask further questions please.
My code:
import numpy as np
from scipy.optimize import minimize
from scipy.optimize import basinhopping
from scipy.integrate import odeint
import pickle
import os
import pandas as pd
import datetime
import numpy.random as npr
import csv
path = "C:\\Users\Sebastian Gäumann\OneDrive\Dokumente\FS 2017\Bachelorarbeit\Python"
os.chdir(path)
###IDS
df = pd.read_csv('1_Youtuber_SingleNrSheet_Comedy.csv', sep = ";", skipinitialspace=True) ######Change Name
YoutuberID = df["Channel_ID"].tolist()
##print(YoutuberID)
with open("9_p_q_m_Fun_ExtendedBass_VIEWS_Comedy_test.csv", "w" ,newline='',encoding='utf-8') as csv_file2: ######Change Name
csv_writer2 = csv.writer(csv_file2, delimiter=';')
csv_writer2.writerow(["Type","p", "q", "m","Functionvalue"])
count = 0
for ID in YoutuberID[0:]: ###Change
try:
path = "C:\\Users\Sebastian Gäumann\OneDrive\Dokumente\FS 2017\Bachelorarbeit\Python"
os.chdir(path)
###ALL INFO
Days = pd.read_csv('3_API_Call_ALL_info_Comedy_v2.csv', sep = ";", skipinitialspace=True)
views_path = "C:\\Users\Sebastian Gäumann\OneDrive\Dokumente\FS 2017\Bachelorarbeit\Python\Daily_Views_Comedy" ######Change Name
os.chdir(views_path)
SVR = pd.read_csv("4_COMEDY_DailyViews_Clean_" + str(count) + "_" + ID + ".csv", sep = ";", parse_dates=True, dayfirst=True) ######Change Name
## print(SVR[SVR.columns[0]])
SVR = SVR[SVR[SVR.columns[0]]< "2018-05-01"] ####CHANGE DATE FOR DIF CAT
## print(SVR)
#####SV Input
SV = np.array(SVR["Daily Views"])
## print(SV)
Days = Days[Days["channelId"] == ID]
## print(Days)
Days["publishedAt"] = pd.to_datetime(Days.publishedAt)
Days = Days[Days["publishedAt"] > "2015-01-08"] ##"2015-01-10"
## print(Days)
##### Timedelta #####
start_date = pd.to_datetime("2015-06-08")
##print(start_date)
video_upload_day =[]
for video_date in Days["publishedAt"]:
TimeDelta = video_date - start_date
video_upload_day.append(TimeDelta.days)
##print(video_upload_day)
##print(videoT)
nvideos = len(video_upload_day)
ndays = len(SV)
videoT = np.array(video_upload_day)
## print(videoT,nvideos,ndays)
def objective(x):
p = x[0]
q = x[1]
m = x[2]
estimateV = np.zeros( (ndays, nvideos) )
for t in range( ndays ):
for v in range( nvideos ):
if videoT[v] <= t:
estimateV[ t,v ] = p*m + (q-p) * np.sum(estimateV[0:t,v],axis=0) - (q/m) * (np.sum(estimateV[0:t,v],axis=0)**2)
estimateSV = np.sum( estimateV, axis = 1 )
return np.sum( (SV - estimateSV)**2 )
This is the minimization part. I made one for the normal minimization and one for basinhopping and seperated it with ##.
###### MINIMIZATION #######
mguess = round(sum(SV)/(nvideos*2),0)
print(sum(SV),mguess)
x0 = np.array([0.001, 0.01, mguess]) ####Make it less volatile to first guess? Make bigger steps for m?
b1 = (0.00001,0.5)
b2 = (10**4,10**7)
bnds = (b1,b1,b2)
## minimizer_kwargs = dict(method="L-BFGS-B",bounds=bnds)
## res = basinhopping(objective, x0,niter=20, minimizer_kwargs=minimizer_kwargs)
res = minimize(objective, x0,bounds = bnds)
print(res)
csv_writer2.writerow(["COMEDY",res.x[0], res.x[1],res.x[2],res.fun]) ###CHANNGE CAT
print("CURRERNT YOUTUBER IS:",count)
count += 1
except:
print("PROBLEM",count)
count += 1
## print(res,res.x[0],res.x[1],res.x[2],res.fun)

Matplotlib animation.FuncAnimation: Custom frame generator only yields once

I'm encountering a strange problem with the matplotlib animation. I'm trying to create a animated bar plot using the following code:
import os, time
from PIL import Image, ImageSequence
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import matplotlib.path as path
import matplotlib.animation as animation
import blackxample
FILE_PREFIX = "cell-isotohyper"
FILE_SUFFIX = ".tif"
FILE_PATH = "./example-video"
XCUT = (91, 91+266)
YCUT = (646, 646+252)
LIMIT = 100
OFFSET = 0
Y_SCALE = 3000
NUM_OF_BINS = 37
BAR_WIDTH = 1.0
BAR_COLOR = 'b'
RANGE = range(0, NUM_OF_BINS//2+1)
def animate(i, fig, ax, bars):
# = np.random.randn(1000)
print(len(i))
for a in RANGE:
bars[a].set_height(i[a])
return (fig, ax, bars)
def main():
fig, ax = plt.subplots()
ax.set_ylim(0, Y_SCALE)
ax.set_xlim(0, NUM_OF_BINS//2+1)
bars = ax.bar(np.arange(NUM_OF_BINS), [i for i in range(NUM_OF_BINS)], BAR_WIDTH, color=BAR_COLOR)
ani = animation.FuncAnimation(fig, animate, xframes, fargs = (fig, ax, bars), interval=500)
plt.show()
This code snippet works completely fine if I'm using randomly generated data or constant via:
def xframes():
i = 0
while i < 100:
yield [2312.7094266223335, 27.238786592368257, 75.252063484372513, 13.678304922077643, 11.879804374653929, 21.900570139020687, 2.930771773796323, 11.945594479736741, 10.88517941461987, 4.4176609254771506, 4.1075871395528338, 1.248363771876285, 1.4798157379442216, 3.5285036346353564, 3.2583080973651732, 3.4640042567344267, 3.130503535456981, 0.67334205875304676, 0.71393606581800562]
#yield np.histogram(np.random.randn(1000), NUM_OF_BINS//2 + 1)[0]
i+=1
Using the function, aframes, instead, does only yield the first item if it is used together animation.FuncAnimation(). If aframe is iterated manually, however, the generator works completely fine.
def aframes():
list_of_files = []
for dirname, dirnames, filenames in os.walk(FILE_PATH):
for filename in filenames:
if filename.startswith(FILE_PREFIX) and filename.endswith(FILE_SUFFIX):
list_of_files.append(os.path.join(FILE_PATH, filename))
# Open every picture - in every file
count = 0
imagecount = 0
framecount = 0
skipped = 0
for file in list_of_files:
framecount = 0
a = Image.open(file)
for frame in ImageSequence.Iterator(a):
if count > OFFSET and count <= OFFSET+LIMIT:
# Cut image beforehand - probably faster
frame = frame.crop((XCUT[0], YCUT[0], XCUT[1], YCUT[1]))
# Load image intro Matrix
imageMatrix = blackxample.Matrix.fromPillow(frame)
try:
imageMatrix.findContour()
imageMatrix.calculateCentroid()
imageMatrix.transform(NUM_OF_BINS)
#yield imageMatrix.getTransform()
yield [2312.7094266223335, 27.238786592368257, 75.252063484372513, 13.678304922077643, 11.879804374653929, 21.900570139020687, 2.930771773796323, 11.945594479736741, 10.88517941461987, 4.4176609254771506, 4.1075871395528338, 1.248363771876285, 1.4798157379442216, 3.5285036346353564, 3.2583080973651732, 3.4640042567344267, 3.130503535456981, 0.67334205875304676, 0.71393606581800562]
except blackxample.NoConvergenceError:
skipped+=1
print("[", count ,"] done")
framecount+=1
count+=1
imagecount+=1
# Test for frame iterator - works fine
#for i in _frames():
# print(i)
Does someone has a clue what and why is happening? How can I fix it?
The generator also runs as expected if the three imageMatrix-lines inside the try-block are commented out which suggests that there is an error inside imageMatrix.findContour(). But what am I looking for? findContour doesn't do anything weird
Since I have not found any solutions regarding this problem, I've decided to save the result of aframes() in a file, then reading and animating it seperatly which works flawlessly without adjusting the animation code.

Resources