Can't make MatPlotLib display mid-function - python

I am writing a programme to input data into a JSON database. Part of this is:
displaying an image (file name entered by user)
asking for coordinates of interest (entered by user)
re-displaying cropped image using those coordinates
asking for tags for this cropped segment (entered by user)
saving tags & coordinates in the JSON database
This same process was used for text files but now that I am doing images I am having the problem that when my programme calls the function:
img = mpimg.imread("raw_data" + system_slash + "images" + system_slash + database[i]['image_file'])
plot.imshow(img)
it does not display the image immediately, but instead only after the whole programme completes. Could anyone suggest a different call to make it display in line, like a print function for text?
*the system slash is a quick and dirty fix for me and my colleague using both PC and MAC file systems when using the programme, so either / or \

After the plotting command, you should put matplotlib.pyplot.pause(t), where t is the time you want to pause. The interval t is in seconds, so if you want for example an animation with roughly 60fps, you could set t=1/60.
The function updates the figure and displays it for t seconds.
EDIT What also came to my mind is: Don't call plt.imshow repeatedly. This is very slow. Better call it once and then just set the data. Little demo:
import matplotlib.pyplot as plt
import numpy as np
im = plt.imshow(np.random.rand(10,10))
while True:
im.set_data(np.random.rand(10,10))
plt.pause(1/10)

Related

Overlay Plot on png image using Matplotlib. Python 2.7

Configuration:
MOXA Debian 9, using Python 2.7 latest version (The software is written in Python2.7) with Matplotlib 2.2.5. The program is not in service anymore, but still works great.
Question:
I want to overlay a generated plot, on top of an png image using matplotlib. This would generate final image
Situation:
The program measures the sky brightness using a sensor and with that data it generates a plot. This every 5 minutes. The plot.py script file is used to build a plot.
I use to just overlay the plot on top of the image at the end of the night using Imagemagick overlay line with a small sh script. But as the program updates the plot every 5 minutes at night, i want to be able to already overlay the plot on top of the image, if possible using matplotlib inside the plot.py script. The plot and the image are both png.
Is this possible? I have investigated this a bit, and i think i need to add some code between line
print('Ploting photometer data ...')
if (input_filename is None):
input_filename = config.current_data_directory+\
'/'+config._device_shorttype+'_'+config._observatory_name+'.dat'
# Define the observatory in ephem
Ephem = Ephemerids()
# Get and process the data from input_filename
NSBData = SQMData(input_filename,Ephem)
# Moon and twilight ephemerids.
Ephem.calculate_moon_ephems(thedate=NSBData.Night)
Ephem.calculate_twilight(thedate=NSBData.Night)
Ephem.calculate_observation(thedate=NSBData.Night)
# Calculate data statistics
NSBData.data_statistics(Ephem)
# Write statiscs to file?
if write_stats==True:
save_stats_to_file(NSBData.Night,NSBData,Ephem)
# Plot the data and save the resulting figure
NSBPlot = Plot(NSBData,Ephem)
Above is the plot generated, and here i think i would need to overlay it before it will be saved as quoted below.
output_filenames = [\
str("%s/%s_%s.png" %(config.current_data_directory,\
config._device_shorttype,config._observatory_name)),\
str("%s/%s_120000_%s-%s.png" \
%(config.daily_graph_directory, str(NSBData.Night).replace('-',''),\
config._device_shorttype, config._observatory_name))\
]
for output_filename in output_filenames:
NSBPlot.save_figure(output_filename)
Is this correct, and how do i do this?
I have found some information: test.png would then be ofcourse the destination location of the image.png. But to be honest, do not know where to start and how to interpreted it.I have read error's of people using plt.show() in the end, but that freezes the system, so i do not need that line.
import matplotlib.pyplot as plt
im = plt.imread('test.png')
implot = plt.imshow(im)
plt.plot([100,200,300],[200,150,200],'o')
Thank you in advance.

Saving image of every python execution in a folder with a serial number as file name

I am a beginner in Python and would like to execute a code which saves an image into particular directory.
The thing is, I would like to save image with a serial number so that I can have many images(each execution gives one image) in the directory.
plt.savefig('Images/Imageplot.png') ## Image saved to particular folder
About the serial number, you can use the uuid library to generate a random and unique id for an image. See more here: https://www.geeksforgeeks.org/generating-random-ids-using-uuid-python/
To save images, it is a bit more complicated. It requires you to import the os library.
Here is an example:
import os
UPLOADED_FILE_DIR_PATH = os.path.join(os.path.dirname(__file__), "static", "uploaded-images")
my_file_path = os.path.join(UPLOADED_FILE_DIR_PATH, my_filename)
image_file.save(my_file_path)
This is a block of code I used previously for my website, so it may not apply for you, depending on your situation. I personnaly like that method, but if you are unsatisfied, take a look at this for more options: https://towardsdatascience.com/loading-and-saving-images-in-python-ba5a1f5058fb

Image not updating in python plot during animation

The Problem:
I'm trying to simulate a live video by cycling through a series of still images I have saved in a directory, but when I add the animation and update functions my plot is displayed empty.
Background on why I'm doing this:
I believe its important for me to do it this way rather than a complete change of approach, say turning the images into a video first then displaying that, because what I really want to test is the image analysis I will be adding and then overlaying on each frame. The final application will be receiving frames one by one from a camera and will need to do some processing, display the image + annotations + output the data as .csv etc... I'm simulating this for now because I do not have any of the hardware to generate the images and will not have it for several months during which time I need to get the image processing set up, but I do have access to some sets of stills that are approximately what will be produced. In case its relevant my simulation images are 1680x1220 and are 1.88 Mb TIFFs, though I could covert and compress them if needed, and in the final form the resolution will be a bit higher and probably the image format could be adjusted if needed.
What I have tried:
I followed an example to list all files in a folder, and an example
to update a plot. However, the plot displays blank when I run the
code.
I added a line to print the current file name, and I can see this
cycling as expected.
I also made sure the images will display in the plot if I just create
a plot and add one image, and they do. But, when combined with the
animation function the plot is blank and I'm not sure what I've done
wrong/failed to include.
I also tried adding a plt.pause() in the update, but again this
didn't work.
I increased the interval up to 2000 to give it more time, but that didn't work. I believe 2000 is extreme, I'm expecting it should work with more like 20-30fps. Going to 0.5fps tells me the code is wrong or incomplete, rather than it just being a question of needing time to read the image file.
I appreciate no one else has my images, but they are nothing special. I'm using 60 images but I guess it could be tested with any 2 random images and setting range(60) to range(2) instead?
The example I copied originally demonstrated the animation function by making a random array, and if I do that it will show a plot that updates with random squares as expected.
Replacing:
A = np.random.randn(10,10)
im.set_array(A)
...with my image instead...
im = cv2.imread(files[i],0)
...and the plot remains empty/blank. I get a window shown called "Figure1" (like when using the random array), but unlike with the array there is nothing in this window.
Full code:
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import os
import cv2
def update(i):
im = cv2.imread(files[i],0)
print(files[i])
#plt.pause(0.1)
return im
path = 'C:\\Test Images\\'
files = []
# r=root, d=directories, f = files
for r, d, f in os.walk(path):
for file in f:
if '.TIFF' in file:
files.append(os.path.join(r, file))
ani = FuncAnimation(plt.gcf(), update, frames=range(60), interval=50, blit=False)
plt.show()
I'm a python and a programming novice so have relied on adjusting examples others have given online but I have only a simplistic understanding of how they are working and end up with a lot of trial and error on the syntax. I just can't figure out anything to make this one work though.
Cheers for any help!
The main reason nothing is showing up is because you never add the images to the plot. I've provided some code below to do what you want, be sure to look up anything you are curious about or don't understand!
import glob
import os
from matplotlib import animation
import matplotlib.image as mpimg
import matplotlib.pyplot as plt
IMG_DIRPATH = 'C:\\Test Images\\' # the folder with your images (be careful about
# putting spaces in directory names!)
IMG_EXT = '.TIFF' # the file extension of your images
# Create a figure, and set to the desired size.
fig = plt.figure(figsize=[5, 5])
# Create axes for the current figure so that images can be sized appropriately.
# Passing in [0, 0, 1, 1] makes the axes fill the whole figure.
# frame_on=False means we won't have a bounding box, and setting xticks=[] and
# yticks=[] means that we won't have pesky tick marks along our image.
ax_props = {'frame_on': False, 'xticks': [], 'yticks': []}
ax = plt.axes([0, 0, 1, 1], **ax_props)
# Get all image filenames.
img_filepaths = glob.glob(os.path.join(IMG_DIRPATH, '*' + IMG_EXT))
def update_image(img_filepath):
# Remove all existing images on the axes, and restore our settings.
ax.clear()
ax.update(ax_props)
# Read the current image.
img = mpimg.imread(img_filepath)
# Add the current image to the plot axes.
ax.imshow(img)
anim = animation.FuncAnimation(fig, update_image, frames=img_filepaths, interval=250)
plt.show()

How to view real time mosaicing of large image?

I have built a code which will stitch 100X100 images approx. I want to view this stitiching process in real time. I am using pyvips to create large image. I am saving final image in .DZI format as it will take very less memory footprint to display.
Below code is copied just for testing purpose https://github.com/jcupitt/pyvips/issues/43.
#!/usr/bin/env python
import sys
import pyvips
# overlap joins by this many pixels
H_OVERLAP = 100
V_OVERLAP = 100
# number of images in mosaic
ACROSS = 40
DOWN = 40
if len(sys.argv) < 2 + ACROSS * DOWN:
print 'usage: %s output-image input1 input2 ..'
sys.exit(1)
def join_left_right(filenames):
images = [pyvips.Image.new_from_file(filename) for filename in filenames]
row = images[0]
for image in images[1:]:
row = row.merge(image, 'horizontal', H_OVERLAP - row.width, 0)
return row
def join_top_bottom(rows):
image = rows[0]
for row in rows[1:]:
image = image.merge(row, 'vertical', 0, V_OVERLAP - image.height)
return image
rows = []
for y in range(0, DOWN):
start = 2 + y * ACROSS
end = start + ACROSS
rows.append(join_left_right(sys.argv[start:end]))
image = join_top_bottom(rows)
image.write_to_file(sys.argv[1])
To run this code:
$ export VIPS_DISC_THRESHOLD=100
$ export VIPS_PROGRESS=1
$ export VIPS_CONCURRENCY=1
$ mkdir sample
$ for i in {1..1600}; do cp ~/pics/k2.jpg sample/$i.jpg; done
$ time ./mergeup.py x.dz sample/*.jpg
here cp ~/pics/k2.jpg will copy k2.jpg image 1600 times from pics folder, so change according to your image name and location.
I want to display this process in real time. Right now after creating final mosaiced image I am able to display. Just an idea,I am thinking to make a large image and display it, then insert smaller images. I don't know, how it can be done. I am confused as we also have to make pyramidal structure. So If we create large image first we have to replace each level images with the new images. Creating .DZI image is expensive, so I don't want to create it in every running loop. Replacing images may be a solution. Any suggestion folks??
I suppose you have two challenges: how to keep the pyramid up-to-date on the server, and how to keep it up-to-date on the client. The brute force method would be to constantly rebuild the DZI on the server, and periodically flush the tiles on the client (so they reload). For something like that you'll also need to add a cache bust to the tile URLs each time, or the browser will think it should just use its local copy (not realizing it has updated). Of course this brute force method is probably too slow (though it might be interesting to try!).
For a little more finesse, you'd want to make a pyramid that's exactly aligned with the sub images. That way when you change a single sub image, it's obvious which tiles need to be updated. You can do this with DZI if you have square sub images and you use a tile size that is some even fraction of the sub image size. Also no tile overlap. Of course you'll have to build your own DZI constructor, since the existing ones aren't primed to simply replace individual tiles. If you know which tiles you changed on the server, you can communicate that to the client (either via periodic polling or with something like web sockets) and then flush only those tiles (again with the cache busting).
Another solution you could experiment with would be to not attempt a pyramid, per se, but just a flat set of tiles at a reasonable resolution to allow the user to pan around the scene. This would greatly simplify your pyramid updating on the server, since all you would need to do would be replace a single image for each sub image. This could be loaded and shown in a custom (non-OpenSeadragon) fashion on the client, or you could even use OpenSeadragon's multi-image feature to take advantage of its panning and zooming, like here: http://www.letsfathom.com/ (each album cover is its own independent image object).

How to extract sketches from shell part in ABAQUS

I have a 2D shell part containing a number of shell faces. I would like to extract one different sketch for each of the faces in the part. So far I know how to create a single sketch containing all the shell faces information but this is not what I want. I would like to know how to create one sketch per shell face. This is what I have done (not right).
stest= model.ConstrainedSketch(name='__polyTest__',sheetSize=2000.0)
mdb.models['Model-1'].parts['Result'].projectReferencesOntoSketch(filter=
COPLANAR_EDGES, sketch=mdb.models['Model-1'].sketches['__polyTest__'])
Many thanks for your help.
Open your part in the current viewport and try this:
from part import *
from sketch import *
p=session.viewports[session.currentViewportName].displayedObject
currentModel=mdb.models[p.modelName]
for faceNum,face in enumerate(p.faces):
try: # Will only work on valid sketch planes. Must be a flat face
t = p.MakeSketchTransform(sketchPlane=face, sketchUpEdge=p.edges[0],
sketchPlaneSide=SIDE1, origin=(659.077803, 0.256062, -816.16))
s = currentModel.ConstrainedSketch(name='__profile__',
sheetSize=834.36, gridSpacing=20.85, transform=t)
edgeList=[p.edges[edgeNum] for edgeNum in face.getEdges()]
p.projectEdgesOntoSketch(sketch=s, edges=tuple(edgeList))
currentModel.ConstrainedSketch(name='Sketch-face' + str(edgeNum), objectToCopy=s)
except:
pass

Categories

Resources