Showing posts with label image. Show all posts
Showing posts with label image. Show all posts

Thursday, February 27, 2025

Can you create animation with Python? Part 1

It is possible to create simple animation with Python easily. This post shows how easy to create simple animation such as a GIF.

As the first step we create a wheel with a single spoke. We will then extend it to create a wheel with 5 spokes. 

The code for creating a circle with one spoke is as shown:

--------------------------------

from PIL import Image, ImageDraw

import numpy as np


def create_one_spoke_image(filename="one_spoke.png"):

    img_size = 500

    center = (img_size // 2, img_size // 2)

    radius = img_size // 4


    img = Image.new("RGB", (img_size, img_size), "white")

    draw = ImageDraw.Draw(img)


    # Draw the circle

    draw.ellipse((center[0] - radius, center[1] - radius, center[0] + radius, center[1] + radius), fill="black")


    # Draw ONE spoke (at 0 degrees for simplicity)

    x1 = center[0]

    y1 = center[1]

    x2 = center[0] + radius  # Spoke extends to the right

    y2 = center[1]

    draw.line((x1, y1, x2, y2), fill="red", width=3)


    img.save(filename)

    print(f"Saved: {filename}")

    img.show()


if __name__ == "__main__":

    create_one_spoke_image()

------------------------------------------------------

Here is the complete explanation of the code:


from PIL import Image, ImageDraw

import numpy as np

from PIL import Image, ImageDraw:

This line imports the Image and ImageDraw classes from the Python Imaging Library (PIL), also known as Pillow.

Image is used to create and manipulate image objects.

ImageDraw is used to draw shapes and lines on those image objects.

import numpy as np:

While numpy is imported, in this specific code provided, it is not actually utilized. If future modifications were to be made to the code, and array manipulation was needed, numpy would then be used.

2. Creating a Blank Image:

img_size = 500

img = Image.new("RGB", (img_size, img_size), "white")

img_size = 500:

This sets the size of the image to 500 pixels by 500 pixels.

img = Image.new("RGB", (img_size, img_size), "white"):

This creates a new image object.

"RGB" specifies that the image will be in RGB color mode (red, green, blue).

(img_size, img_size) sets the dimensions of the image.

"white" sets the initial background color of the image to white.

3. Creating a Draw Object:

draw = ImageDraw.Draw(img)

draw = ImageDraw.Draw(img):

This creates a Draw object associated with the img image.

The Draw object provides methods for drawing shapes, lines, and text onto the image.

4. Drawing a Circle:

center = (img_size // 2, img_size // 2)

radius = img_size // 4

draw.ellipse((center[0] - radius, center[1] - radius, center[0] + radius, center[1] + radius), fill="black")

center = (img_size // 2, img_size // 2):

This calculates the center coordinates of the image.

radius = img_size // 4:

This calculates the radius of the circle, which is one-quarter of the image size.

draw.ellipse(...):

This draws an ellipse (which will be a circle in this case, due to the equal width and height).

The coordinates (center[0] - radius, center[1] - radius, center[0] + radius, center[1] + radius) define the bounding box of the ellipse.

fill="black" sets the fill color of the circle to black.

5. Drawing a Spoke:

x1 = center[0]

y1 = center[1]

x2 = center[0] + radius  # Spoke extends to the right

y2 = center[1]

draw.line((x1, y1, x2, y2), fill="red", width=3)

x1 = center[0], y1 = center[1]:

These set the starting coordinates of the line (the spoke) to the center of the image.

x2 = center[0] + radius, y2 = center[1]:

These set the ending coordinates of the line. The spoke extends horizontally to the right, to the edge of the circle.

draw.line(...):

This draws a line between the starting and ending coordinates.

fill="red" sets the color of the line to red.

width=3 sets the thickness of the line to 3 pixels.

6. Saving the Image:

img.save(filename)

print(f"Saved: {filename}")

img.show()

img.save(filename):

This saves the created image to a file with the specified filename.

print(f"Saved: {filename}"):

This prints a confirmation message to the console.

img.show(): This line displays the image on a related printer as shown.

--------------------------------------------------------

When you run this code you will see the following:

C:\Users\hoden\AppData\Local\Programs\Python\Python312\python.exe C:\Users\hoden\PycharmProjects\exploreImage\Images\CircleOneSpoke.py 
Saved: one_spoke.png
Process finished with exit code 0

The following image is displayed:








Monday, December 23, 2024

Do you want to slow down a fast GIF?

GIFs are very engaging and dynamic images and they can run at a speed set at the time of creation. Well, some GIFs may look way better when run at a slow speed. 

You can use Python code to slow down a GIF that is too fast for your liking. In the previous post, you learnt how to make a GIF from scratch using Python. In this post, you will use Python code to slow down a GIF. The post shows an example.

Here is a GIF that is somewhat fast. It is copied from a website. 

Now here is the Python code that you can use to slow it down. The code shown is copied from my PyCharm user interface. If you copy and paste make sure the indentation requirements are satisfied.

from PIL import Image, ImageSequence
# Open the original GIF gif_path = 'lawn-time-lapse.gif'
gif = Image.open(r'C:\Users\hoden\PycharmProjects\exploreImage\Images\lawn-time-lapse.gif')
# Create a list to hold the frames
frames = []
# Loop through each frame in the original GIF
for frame in ImageSequence.Iterator(gif):
# Append each frame to the list
frames.append(frame.copy())
# Save the frames as a new GIF with a slower speed
frames[0].save('slowed_down_1_gif.gif', save_all=True, append_images=frames[1:],
duration=200, loop=0)
print('Slowed down GIF saved as slowed_down_1_gif.gif')

The fast GIF is in the project folder in the path shown. The ImageSequence is the key. You get a sequence of images in the frame that you append to a list. Save the frames as a new GIF with a slower speed. Duration in PIL is absolute in milliseconds.

The code before the print saves the first frame(frames[0]) and it saves all the frames slowing down to a duration of 200 seconds and appends the rest of the frames starting from frame[1], the second frame in the sequence.

Here is the result of slowing down the original GIF.


Since we have a handle to the sequence, we can find the original frames and the original duration as well.


Monday, June 17, 2024

Can you call Python libraries from Python Scratch files?

 I see no reason why Python libraries can not be called from Scratch files.  

Let me try using my existing Scratch.py (https://hodentekhelp.blogspot.com/2024/06/what-is-scratch-file-in-pycharm.html) to call the PIL library.


You see you can do it. 


However, you see an indent error. This is not a serious error. It just says there is an unexpected indent.  You can get rid of this error by moving the line "from PIL import Image" back one step, by removing the white space before "from".

This brings another weak warning (Yellow upright triangle with a ! inside). This is a weak warning and not an error. The call statement should be the first statement.

Now remove the print("Scratchy". This clears the weak warning.


Now that the calling of Image is successful, let us explore Image a little bit.

Using Image

The PyCharm provides a drop-down for facilitating code and you should watch out.

Let me see if I can Open an image on my desktop (C:\Users\hoden\OneDrive\Desktop\Beware.jpg).


To open an image you would use the open() method. You should use the image path as an argument in open().

The image we are using Beware.jpg is on the desktop and its location is

 "C:\Users\hoden\OneDrive\Desktop\Beware.jpg"


You get a bunch of errors for each "/" in the path. This needs to be corrected. The next image file specification removes the bunch of indent errors.


Each indent is replaced by // as shown above.

The code runs without errors. To see the image, we need to call another library. For now, since we have image, let me get the width and height of the image by the following code (you need not display the image to get its properties):

=========================================================

from PIL import Image

image_path = "C://Users//hoden//OneDrive//Desktop//Beware.jpg"

image=Image.open(image_path)

width, height = image.size

print(f"Image dimensions: Width = {width}, Height = {height}")

==========================================================

This code runs as well and you get the Height and width as,

Height= 259  Width=  259

The units are in pixels.

The height and width of the image from its properties using Windows explorer is shown here.


Important thing to note:

File references may sometime gets tricky as the file may be on the desktop, or some other location. It is best to catch an error, if the file is not at the expected location. 




Saturday, June 8, 2024

How do you install Python Image Library for PyCharm?

 PIL, or Python Image Library provides support for working with images in Python (Interpreter). PIL provides a fairly fast and powerful way to process images.

You may also come across Pillow. Pillow (a fork of PIL) is same as PIL, and it was created since PIL was not supported since 2009.You use Pillow wherever you need PIL. Pillow is supported by active developers.

Importantly Pillow provides,

File format support.

Image processing capabilities.

In an earlier post we have seen many of the desirable features of PyCharm. Other libraries for processing images in Python are OpenCV and matplotlib.

PIL Installation:

Using PIP, PIL can be installed. Installing Pillow (or PIL) is easy and with a simple command,

pip install Pillow

However, you may have to use it with caution.

PIL,  or Pillow with PyCharm:

If you have PyCharm installed, it is fairly easy to install PIL. The highligted in blue is the node for Phyton Packages.


You find Pillow at the end of the listt of packages available in this node.


If you click Install (blue lin) it opens a drop-down list as shown.


From PIL 1.0 to 10.3.0 versions can be installed. What is the best version then? It would be the latest since Pillow is maintained with all bug fixes. If you need to work with older projects you may need to dig a little deeper as there may be compatibility issues with Python versions.

Herein the latest version will be used and if some problems arise other versions may be considered.

Clicking on 10.3.0 installs this version of Pillow. Easy, isn't it?


How do you check if Pillow is installed?

Just try to run the following code from the Python Console shown in blue, 

from PIl import Image

You should see the success of your code.

Visit again for more PyCharm and PIL.

Wednesday, May 23, 2018

What data types can we use in a SQL Server 2016 database table?

Based on the table design using SQL Server Management Studio, v17.7, the following data types can be identified. These are the ones you find in SQL Server 17 as well.


Data types (text,ntext, image) continues to be present although Microsoft has been saying that they will be deprecated in a future version of SQL Server. 

Friday, March 23, 2018

How do I display using code an image from the Assets in a UWP project?


Let us take the simple example of a button click event displaying an image stored in the project's Asset folder on the page.

At a minimum we create a UWP Blank project. Then we add a StackPanel. In the StackPanel we place two named elements, a button and an image by providing the NAME property for the controls.

Basic Page design MainPage.xaml



Add an external image to Asset folder (you could also use an existing image)

We bring in an external image into the Asset Folder using:


Since we configured a click event in the XAML, this BTN_Click event code will be present in the MainPage.xaml.cs as shown.

Add code to MainPage,xaml.cs


We create an instance of Image as a new image. The source for this image has to change from System.Uri to Windows.Foundation.Uri that UWP requires and hence the conversion. 


However, code needs fixing, and there is a fix with a link. You can safely click this to modify. This includes a new using reference (using Windows.UI.Xaml.Media.Imaging) as shown. 

The this.BaseURI is now referencing the ASSETS folder's content that we added as shown.


Build, Deploy and RUN

This completes the code and the Project builds without errors. When you run it in the Local Machine as you have done with the others you see this page.

App Display

App Display after button click




Saturday, August 16, 2008

How does an Access table copy over to MS SQL Server 2008?

Here is an example of how Categories table in Northwind database would copy over to the SQL Server 2008 Database Nwind2008.

MS Access:

Category ID  Primary Key Data Type: AutoNumber Long Integer Indexed:Yes(No dups)
CategoryName: Data Type: Text FieldSize:15 AllowZeroLength:No Indexed:Yes(No dups)
Required:Yes
Descripton: Data Type:Memo AllowZeroLength+NO, Indexed:No, Required:no
Picture: OLE Object Required:NO

SQL Server 2008:
CategoryID: Int AllowNulls:NO
CategoryName: nvarchar(15) AllowNulls:No
Description: nvarchar(MAX) allowNulls:Yes
Picture: Data Type: image Allow Nulls:Yes