Python PIL | ImageOps.fit () method

| | | | |

👻 Check our latest review to choose the best laptop for Machine Learning engineers and Deep learning tasks!

ImageOps.fit() returns ImageOps.fit() and a cropped version of the image cropped to the requested aspect ratio and size.

Syntax : PIL.ImageOps.fit (image, size, method = 0, bleed = 0.0, centering = (0.5, 0.5))

Parameters :
image - The image to size and crop.
size - The requested output size in pixels, given as a (width, height) tuple.
method - What resampling method to use. Default is PIL.Image.NEAREST.
bleed - Remove a border around the outside of the image from all four edges.
centering - Control the cropping position.

  • Use (0.5, 0.5) for center cropping (eg if cropping the width, take 50% off of the left side, and therefore 50% off the right side).
  • (0.0, 0.0) will crop from the top left corner (ie if cropping the width, take all of the crop off of the right side, and if cropping the height, take all of it off the bottom).
  • (1.0, 0.0) will crop from the bottom left corner, etc. (ie if cropping the width, take all of the crop off the left side, and if cropping the height take none from the top, and therefore all off the bottom).

Returns : An image.

Image in use:

# Import Image and ImageOps module from PIL

from PIL import Image, ImageOps


# create image1 object

im1 = Image. open (r "C: UsersSystem-PcDesktop circleimage.PNG " )


# applying the pick method
# Setting width = 100 and height = 100

im2 = ImageOps.fit (im1, ( 100 , 100 ), method = 0 ,

bleed = 0.0 , centering = ( 0.5 , 0.5 ))


im 2.show ()

Output:

👻 Read also: what is the best laptop for engineering students?

Python PIL | ImageOps.fit () method around: Questions

Removing white space around a saved image in matplotlib

2 answers

I need to take an image and save it after some process. The figure looks fine when I display it, but after saving the figure, I got some white space around the saved image. I have tried the "tight" option for savefig method, did not work either. The code:

  import matplotlib.image as mpimg
  import matplotlib.pyplot as plt

  fig = plt.figure(1)
  img = mpimg.imread(path)
  plt.imshow(img)
  ax=fig.add_subplot(1,1,1)

  extent = ax.get_window_extent().transformed(fig.dpi_scale_trans.inverted())
  plt.savefig("1.png", bbox_inches=extent)

  plt.axis("off") 
  plt.show()

I am trying to draw a basic graph by using NetworkX on a figure and save it. I realized that without a graph it works, but when added a graph I get white space around the saved image;

import matplotlib.image as mpimg
import matplotlib.pyplot as plt
import networkx as nx

G = nx.Graph()
G.add_node(1)
G.add_node(2)
G.add_node(3)
G.add_edge(1,3)
G.add_edge(1,2)
pos = {1:[100,120], 2:[200,300], 3:[50,75]}

fig = plt.figure(1)
img = mpimg.imread("image.jpg")
plt.imshow(img)
ax=fig.add_subplot(1,1,1)

nx.draw(G, pos=pos)

extent = ax.get_window_extent().transformed(fig.dpi_scale_trans.inverted())
plt.savefig("1.png", bbox_inches = extent)

plt.axis("off") 
plt.show()
228

Answer #1

You can remove the white space padding by setting bbox_inches="tight" in savefig:

plt.savefig("test.png",bbox_inches="tight")

You"ll have to put the argument to bbox_inches as a string, perhaps this is why it didn"t work earlier for you.


Possible duplicates:

Matplotlib plots: removing axis, legends and white spaces

How to set the margins for a matplotlib figure?

Reduce left and right margins in matplotlib plot

228

Answer #2

I cannot claim I know exactly why or how my “solution” works, but this is what I had to do when I wanted to plot the outline of a couple of aerofoil sections — without white margins — to a PDF file. (Note that I used matplotlib inside an IPython notebook, with the -pylab flag.)

plt.gca().set_axis_off()
plt.subplots_adjust(top = 1, bottom = 0, right = 1, left = 0, 
            hspace = 0, wspace = 0)
plt.margins(0,0)
plt.gca().xaxis.set_major_locator(plt.NullLocator())
plt.gca().yaxis.set_major_locator(plt.NullLocator())
plt.savefig("filename.pdf", bbox_inches = "tight",
    pad_inches = 0)

I have tried to deactivate different parts of this, but this always lead to a white margin somewhere. You may even have modify this to keep fat lines near the limits of the figure from being shaved by the lack of margins.

How to do a scatter plot with empty circles in Python?

2 answers

In Python, with Matplotlib, how can a scatter plot with empty circles be plotted? The goal is to draw empty circles around some of the colored disks already plotted by scatter(), so as to highlight them, ideally without having to redraw the colored circles.

I tried facecolors=None, to no avail.

204

Answer #1

From the documentation for scatter:

Optional kwargs control the Collection properties; in particular:

    edgecolors:
        The string ‘none’ to plot faces with no outlines
    facecolors:
        The string ‘none’ to plot unfilled outlines

Try the following:

import matplotlib.pyplot as plt 
import numpy as np 

x = np.random.randn(60) 
y = np.random.randn(60)

plt.scatter(x, y, s=80, facecolors="none", edgecolors="r")
plt.show()

example image

Note: For other types of plots see this post on the use of markeredgecolor and markerfacecolor.

plot a circle with pyplot

2 answers

surprisingly I didn"t find a straight-forward description on how to draw a circle with matplotlib.pyplot (please no pylab) taking as input center (x,y) and radius r. I tried some variants of this:

import matplotlib.pyplot as plt
circle=plt.Circle((0,0),2)
# here must be something like circle.plot() or not?
plt.show()

... but still didn"t get it working.

199

Answer #1

You need to add it to an axes. A Circle is a subclass of an Patch, and an axes has an add_patch method. (You can also use add_artist but it"s not recommended.)

Here"s an example of doing this:

import matplotlib.pyplot as plt

circle1 = plt.Circle((0, 0), 0.2, color="r")
circle2 = plt.Circle((0.5, 0.5), 0.2, color="blue")
circle3 = plt.Circle((1, 1), 0.2, color="g", clip_on=False)

fig, ax = plt.subplots() # note we must use plt.subplots, not plt.subplot
# (or if you have an existing figure)
# fig = plt.gcf()
# ax = fig.gca()

ax.add_patch(circle1)
ax.add_patch(circle2)
ax.add_patch(circle3)

fig.savefig("plotcircles.png")

This results in the following figure:

The first circle is at the origin, but by default clip_on is True, so the circle is clipped when ever it extends beyond the axes. The third (green) circle shows what happens when you don"t clip the Artist. It extends beyond the axes (but not beyond the figure, ie the figure size is not automatically adjusted to plot all of your artists).

The units for x, y and radius correspond to data units by default. In this case, I didn"t plot anything on my axes (fig.gca() returns the current axes), and since the limits have never been set, they defaults to an x and y range from 0 to 1.

Here"s a continuation of the example, showing how units matter:

circle1 = plt.Circle((0, 0), 2, color="r")
# now make a circle with no fill, which is good for hi-lighting key results
circle2 = plt.Circle((5, 5), 0.5, color="b", fill=False)
circle3 = plt.Circle((10, 10), 2, color="g", clip_on=False)
    
ax = plt.gca()
ax.cla() # clear things for fresh plot

# change default range so that new circles will work
ax.set_xlim((0, 10))
ax.set_ylim((0, 10))
# some data
ax.plot(range(11), "o", color="black")
# key data point that we are encircling
ax.plot((5), (5), "o", color="y")
    
ax.add_patch(circle1)
ax.add_patch(circle2)
ax.add_patch(circle3)
fig.savefig("plotcircles2.png")

which results in:

You can see how I set the fill of the 2nd circle to False, which is useful for encircling key results (like my yellow data point).

We hope this article has helped you to resolve the problem. Apart from Python PIL | ImageOps.fit () method, check other around-related topics.

Want to excel in Python? See our review of the best Python online courses 2022. If you are interested in Data Science, check also how to learn programming in R.

By the way, this material is also available in other languages:



Jan Innsbruck

Tallinn | 2022-11-30

around is always a bit confusing 😭 Python PIL | ImageOps.fit () method is not the only problem I encountered. I just hope that will not emerge anymore

Oliver Galleotti

Paris | 2022-11-30

Simply put and clear. Thank you for sharing. Python PIL | ImageOps.fit () method and other issues with circle was always my weak point 😁. Checked yesterday, it works!

Walter Krasiko

Rome | 2022-11-30

Maybe there are another answers? What Python PIL | ImageOps.fit () method exactly means?. Will use it in my bachelor thesis

Shop

Learn programming in R: courses

$

Best Python online courses for 2022

$

Best laptop for Fortnite

$

Best laptop for Excel

$

Best laptop for Solidworks

$

Best laptop for Roblox

$

Best computer for crypto mining

$

Best laptop for Sims 4

$

Latest questions

NUMPYNUMPY

Common xlabel/ylabel for matplotlib subplots

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

12 answers

NUMPYNUMPY

Flake8: Ignore specific warning for entire file

12 answers

NUMPYNUMPY

glob exclude pattern

12 answers

NUMPYNUMPY

How to avoid HTTP error 429 (Too Many Requests) python

12 answers

NUMPYNUMPY

Python CSV error: line contains NULL byte

12 answers

NUMPYNUMPY

csv.Error: iterator should return strings, not bytes

12 answers

News


Wiki

Python | How to copy data from one Excel sheet to another

Common xlabel/ylabel for matplotlib subplots

Check if one list is a subset of another in Python

sin

How to specify multiple return types using type-hints

exp

Printing words vertically in Python

exp

Python Extract words from a given string

Cyclic redundancy check in Python

Finding mean, median, mode in Python without libraries

cos

Python add suffix / add prefix to strings in a list

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

Python - Move item to the end of the list

Python - Print list vertically