I want to automate one process, and I need to place some kind of pointer on my image. I found a great solution which works exactly as I would like, but its disadvantage is that it destroys my picture quality. I want to keep same size of the build in picture.
Bellow I share my code and error, which I receive. I would be grateful for your help :)
from matplotlib import image
from matplotlib import pyplot as plt
from PIL import Image
# to read the image stored in the working directory
# data = image.imread(file_name)
data = Image.open('File_name')
x, y = data.size
# to draw a point on co-ordinate (200,300)
plt.figure(figsize=(x, y))
plt.plot(650, 310, marker='*', color="red")
# plt.axis('off')
plt.imshow(data)
File = "File_name"
plt.savefig(File)
plt.show()
ValueError: Image size of 105480x55224 pixels is too large. It must be less than 2^16 in each direction.
How do I convert a 3D object in any STL file into a JPG or PNG image.
I tried searching a little bit online but I wasn't been able to arrive at finding any possible solutions.
Can anyone help me with the code that can do this straight forward task with Python? IS there any libraries that can help with that?
EDIT :
Code Sample:
from mpl_toolkits import mplot3d
from matplotlib import pyplot
import pathlib
DIR = str(pathlib.Path(__file__).parent.resolve()).replace('\\', '/')
path = f'{DIR}/any_stl_file.stl'
# Create a new plot
figure = pyplot.figure()
axes = mplot3d.Axes3D(figure)
# Load the STL files and add the vectors to the plot
your_mesh = mesh.Mesh.from_file(path)
axes.add_collection3d(mplot3d.art3d.Poly3DCollection(your_mesh.vectors))
# Auto scale to the mesh size
scale = your_mesh.points.flatten()
axes.auto_scale_xyz(scale, scale, scale)
pyplot.savefig(f"{DIR}/the_image.jpg")```
Take a look at https://pypi.org/project/numpy-stl/
This code snippet is from the link above:
from stl import mesh
from mpl_toolkits import mplot3d
from matplotlib import pyplot
# Create a new plot
figure = pyplot.figure()
axes = mplot3d.Axes3D(figure)
# Load the STL files and add the vectors to the plot
your_mesh = mesh.Mesh.from_file('tests/stl_binary/HalfDonut.stl')
axes.add_collection3d(mplot3d.art3d.Poly3DCollection(your_mesh.vectors))
# Auto scale to the mesh size
scale = your_mesh.points.flatten()
axes.auto_scale_xyz(scale, scale, scale)
# Show the plot to the screen
pyplot.show()
To save a pyplot object as an image:
pyplot.savefig("file_name.jpg")
I'm trying to save my result image using matplotlib.pyplot as the following code which works good without any problem
import matplotlib.pyplot as plt
I = image.astype(np.uint8)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.imshow(I)
plt.plot(marker_x, marker_y, color='yellow')# our circle
ax.set_title('Macula')
plt.savefig("J://uni//final project//res_image//marked_M.png")
fig.show()
here is my saved picture plt.savefig("J://uni//final project//res_image//marked_M.png") :
the yellow circle is a plot and as you know when we use plt.plot automatically we have a white space around the main picture (sth like margin as you see in the picture ) and also the axes
and its my 'tkinter' UI:
I'm wondering if is any way to crop this annoying white space or save image in another way that we get rid of this margin?
You can use the matplotlib transparent flag
plt.savefig("J://uni//final project//res_image//marked_M.png", transparent=True)
This will save the image as a png file with a transparent background
This question already has answers here:
How to adjust padding with cutoff or overlapping labels
(8 answers)
Closed 4 years ago.
I am making figures for publication. I need the final figure, including the titles and text to be 3 inches wide and saved as a .tiff file. I know I can specify the size of the plot via matplotlib using
matplotlib.pyplot.figure(figsize=(3,2), dpi=300)
However this only specifies the size of the actual plot, not including the titles and everything. Also, the titles get cut off of my saved .tiff file when I try this method. Of course the easy fix is to decrease the size of the plot and manually make the figure the correct size, but does anyone know of an automatic way to make the plot be a given final size with all the bells and whistles included?
Here is the output image which is saved (this one is a png so it can upload to stackoverflow). Note the plot titles are cut off for some reason.
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from PIL import Image
from io import BytesIO
bent=[2.83263904,2.75860489,2.64546045,2.4949913,2.34923737,2.16430217,2.02562783,1.82478841,1.70324689,1.70315642,1.39739535,1.33945747,1.22295623,1.15726486,1.08449954,0.96155077,0.90325786,0.84547091]
bent=[i/27 for i in bent]
print(bent)
planar=[4.11233905,3.93027011,3.65135645,3.38525615,3.1130921,2.81042899,2.58995789,2.36159934,2.15981447,1.9964454,1.74375941,1.63263452,1.48503205,1.38596544,1.26501988,1.17391638,1.07490417,0.99369748]
planar=[i/27 for i in planar]
bi=[2.51027966,2.56495852,2.47033072,2.33008642,2.19395126,2.13732249,1.80922673,1.76037446,1.52930137,1.56732451,1.33905847,1.24952153,1.15699233,1.08251496,0.98449116,0.93838164,0.86542147,0.725736]
bi=[i/34 for i in bi]
T=[3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
arr=[bi,bent,planar]
arr=np.array(arr)
arr=arr.T
font = {'family' : 'normal',
'weight' : 'normal',
'size' : 8}
matplotlib.rc('font', **font)
fig = plt.figure(figsize=(3,2), dpi=300)
plt.title("-ΔS$_m$ vs T") #for Fe$_4$Gd
plt.xlabel('Temperature (K)')
plt.ylabel("$-ΔS_m$ ($J.K^{-1}.mol^{-1}n (e^{-})^{-1}$)")
MMM=('Fe$_4$Gd$_2$','Fe$_4$Gd bent','Fe$_4$Gd planar')
plt.plot(T,arr,'o')
plt.legend(MMM, loc='best')
# save figure
# (1) save the image in memory in PNG format
png1 = BytesIO()
fig.savefig(png1, format='png')
# (2) load this image into PIL
png2 = Image.open(png1)
# (3) save as TIFF
png2.save('TESTTESTTEST.tiff')
png1.close()
Use plt.tight_layout(). You can find more details here.
I have a program using PtQt that utilizes matplotlib to do some plot rendering. For saving images, I would like to make use of the legend to render a custom image (additionally the built-in draggable feature makes this very appealing). I'm reading up on the legend, but I can't seem to figure out how to make a legend that calls my own paintEvent() method for Qt in which I can render custom images.
In case this approach is terrible, here's my goal: I want to put a image (rendered inside the program by Qt) either inside the plot window or find a way to append this image on top of the exported figure.
Here's a screenshot of what the output looks like now:
I'd like to take the DAIP... sequence at the top and have that exported with the figure.
Hopefully someone has tackled a similar problem before.
I solved it by using the OffsetImage and AnnotationBBox features of matplotlib after saving the image to a temporary png file. For some reason keeping it as a temporary file didn't work well.
Briefly:
#draw stuff onto QPixmap named pix
byteArray = QByteArray()
buffer = QBuffer(byteArray)
buffer.open(QIODevice.WriteOnly)
pix.save(buffer, 'PNG')
stringIO = StringIO(byteArray)
stringIO.seek(0)
tfile = tempfile.NamedTemporaryFile(suffix=".png", mode="wb", delete=False)
tfile.write(stringIO.buf)
tfile.close()
imagebox = mpl.offsetbox.OffsetImage(mpl._png.read_png(tfile.name),zoom=zlvl)
ab = mpl.offsetbox.AnnotationBbox(imagebox, [w/2,0],frameon=False)
ab.set_figure(self.canvas.figure)
ab.draggable()
self.subplot.axes.add_artist(ab)
os.remove(tfile.name)