Sunday, January 12, 2025

Are you ready creating a label using Python?

 I assume you've read my previous post, "Is Python a language for creating GUIs?" If so, I invite you to create a label using Python and Kivy. In my previous post, I demonstrated how to install Kivy in the PyCharm IDE, and we shall start from there. However, it is not necessary to use PyCharm to create a label; it can also be done using the command line if you have Kivy and Python installed on your computer. PyCharm is particularly useful if you plan to create multiple projects and more involved programs.

Why a Label?

GUIs comprise many kinds of widgets, and perhaps the label is one of the most common and obvious elements. Labels can be seen individually or as part of larger widgets with smaller sub-widgets, such as in a form or an authentication GUI.

In its most basic form, a label is a small object that usually carries a piece of text, such as 'Welcome' or 'Hello World.' It may even carry a small image.

How do you create a label using Python?

As mentioned earlier you need Python to create a label but need a library such as Kivy. It is assumed that you have both Python and Kivy installed on your computer/laptop. Since, PyCharm is used in this example as the IDE, you create a Python file in a project in PyCharm. 

Python is a declarative language and you create upfront your python file, LabelBasic.py shown here:

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

import kivy
from kivy.app import App
from kivy.uix.label import Label


class MyApp(App):

def build(self):
return Label(text='This is a basic label')


if __name__ == '__main__':

    MyApp().run()

These are basic things happenings:

1. You import necessary modules:

import kivy: imports Kivy library which provides tools for cross-platform GUIS.

import kivy.app import App: imports the App Class for creating kivy applications.

import kivy.uix.label import label: imports label Class to display text or images on the GUI.

2. class MyApp(App): Creates a class named MyApp that inherits from App class represent kivy application.

   def build(self): This method is required in every kivy app. It is called when the application starts and is responsible for building the user interface.

   return label(text='This is a basic label'): This creates an instance of the label class and sets its text property to 'This is a basic label'. This Label instance is then returned as the root widget of the application's UI.

3. Running the application:

  if __name__=='__main__': ensures that the following code is executed only when the script is run directly.

  MyApp().run(): creates an instance of the MyApp class and calls its run() method. This starts the Kivy application and displays the GUI.

This is the standard way of creating a GUI using Python code and the Kivy library. The PyCharm IDE has been used because all the previous posts were written to demonstrate many other types of applications such as Image studies. It is not necessary for creating a GUI element. It can be run if you have Python installed using the command-line.

The basic premise behind this code is creating an object class and instantiating the class and calling its properties to create a kivy widget.


Result of running the code:


The exception thrown running this code  in PyCharm is shown here:

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

C:\Users\hoden\AppData\Local\Programs\Python\Python312\python.exe C:\Users\hoden\PycharmProjects\PyWidgets\LabelBasic.py 

[INFO   ] [Logger      ] Record log in C:\Users\hoden\.kivy\logs\kivy_25-01-12_11.txt

[INFO   ] [deps        ] Successfully imported "kivy_deps.angle" 0.4.0

[INFO   ] [deps        ] Successfully imported "kivy_deps.glew" 0.3.1

[INFO   ] [deps        ] Successfully imported "kivy_deps.sdl2" 0.8.0

[INFO   ] [Kivy        ] v2.3.1

[INFO   ] [Kivy        ] Installed at "C:\Users\hoden\AppData\Local\Programs\Python\Python312\Lib\site-packages\kivy\__init__.py"

[INFO   ] [Python      ] v3.12.0 (tags/v3.12.0:0fb18b0, Oct  2 2023, 13:03:39) [MSC v.1935 64 bit (AMD64)]

[INFO   ] [Python      ] Interpreter at "C:\Users\hoden\AppData\Local\Programs\Python\Python312\python.exe"

[INFO   ] [Logger      ] Purge log fired. Processing...

[INFO   ] [Logger      ] Purge finished!

[INFO   ] [Factory     ] 195 symbols loaded

[INFO   ] [Image       ] Providers: img_tex, img_dds, img_sdl2, img_pil (img_ffpyplayer ignored)

[INFO   ] [Text        ] Provider: sdl2

[CRITICAL] App.root must be an _instance_ of Widget

 Traceback (most recent call last):

   File "C:\Users\hoden\PycharmProjects\PyWidgets\LabelBasic.py", line 13, in <module>

     MyApp().run()

   File "C:\Users\hoden\AppData\Local\Programs\Python\Python312\Lib\site-packages\kivy\app.py", line 955, in run

     self._run_prepare()

   File "C:\Users\hoden\AppData\Local\Programs\Python\Python312\Lib\site-packages\kivy\app.py", line 931, in _run_prepare

     raise Exception('Invalid instance in App.root')

 Exception: Invalid instance in App.root


Process finished with exit code 1

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

There have been many instances where trying to run this simple code has resulted in the same kind of problem with the exception that ' Invalid instance in App.root. Process finished with exit code 1.

Here are the attempts:

1.https://stackoverflow.com/questions/70997766/why-do-i-get-the-error-invalid-instance-in-app-root-in-kivy-python/79331939#79331939

2. Here are few other examples of code failure:

What is the solution?

I have been looking at this problem and trying to diagnose and finally arrived at a work around. I basically suspect that the Run() method has some basic problem and I have been able to work around to make the display the label. My workaround needs introducing a Python decorator '@property' after the class statement but before the widget's build, def build(self).

The Modified code that runs error free:

import kivy
from kivy.app import App
from kivy.uix.label import Label


class MyApp(App):
@property
def build(self):
return Label(text='This is a basic label')


if __name__ == '__main__':
MyApp().run()

When this is run, the Process finished with exit code 0 and you see the following display.


This is indeed a successful run as the label is displayed. I have gone back to Stack Overflow and made some of the cold files to work with this fix.



Saturday, January 11, 2025

Is Python a language for GUI development?

 

The introduction of Computer applications with a graphic user interface was significant milestone in moving Computers and their utility from specialists and technologists to the general public. This was significantly impacted by the 'Desktop' revolution that shifted requirements from Main Frame to Tabletop devices. This also shifted the computer applications from procedural languages to more 'Object' based or object oriented languages and ushered the Internet revolution and presently enjoys enormous popularity because of their utility in every aspect of life.

GUIs simplified interactions with computers, making them more intuitive and user-friendly and led to the democratization of computer access. GUIs in Internet based applications propelled their utility in World Wide Web, e-commerce, social media and online communications and learning.

In the early days, GUIs were exclusively built using low-level languages such as C and C++. With the introduction of higher-level languages like Visual Basic and Java, object creation became significantly easier. The development of the Document Object Model (DOM) further facilitated the integration of GUIs into the Internet through web-based languages like JavaScript.

Python, being an interpreted language, doesn't come with built-in GUI elements. However, it boasts a rich ecosystem of libraries that enable the creation of sophisticated GUIs. Libraries such as Tkinter, PyQt, and Kivy offer powerful tools for developing graphical interfaces in Python.

For example:

Tkinter: A standard Python interface to the Tk GUI toolkit, great for simple applications.[https://wiki.python.org/moin/TkInter]

PyQt: A set of Python bindings for the Qt application framework, suitable for more complex and feature-rich applications.[https://en.wikipedia.org/wiki/PyQt]

Kivy: An open-source Python library for developing multitouch applications, excellent for mobile and cross-platform apps.[https://kivy.org/]

By leveraging these libraries, developers can create GUIs with superior qualities, making Python a versatile choice for both backend and frontend development. Such integration would require connection to databases and web interactions.

These libraries have means for making such a thing possible.

  • Tkinter can connect to SQLite and interact with web making requests and urllib
  • PyQt has more advanced option supporting network operations like PyQt Network and SQLAlchemy for database interactions. 
  • Kivy also uses SQLAlchemy or peewee for database interactions and requests for web interaction
For starters we will be looking at Kivy in my future posts.




Sunday, January 5, 2025

As an App developer have you tried python library KIVY? Do you know how to install it on PyCharm?

 

There are many platforms for writing Apps for mobile phones and KIVY is a open-source Python library. It can be used for developing multitouch apps on mobile devices. It's strength is once created it can run on various platforms including Windows, macOS, Linux, Android and iOS. 

Key Features of Kivy:

  • Cross-Platform: Kivy allows you to write your code once and run it on multiple platforms without modification. This is incredibly useful for developers who want to reach a broad audience.
  • Multitouch Support: Kivy is designed with multitouch in mind, making it ideal for applications that require touch input, such as mobile apps and interactive kiosks.
  • Customizable Widgets: Kivy provides a wide range of customizable widgets, allowing developers to create unique and visually appealing user interfaces. Note: It has no Radio Button.
  • GPU Acceleration: Kivy uses OpenGL to provide GPU-accelerated graphics, ensuring smooth and responsive user interfaces.
  • Community and Documentation: Kivy has a strong community and extensive documentation, making it easier for developers to find support and resources.

Is Python for GUI devleopment?

It is versatile, easy to design with straight forward syntax and run smoothly and responsively. It has the capability for multitouch and is made for 'Mobile' apps.

This post shows you how to import the KIVY library into PyCharm. PyCharm has native support for KIVY and getting it into PyCharm is a piece of cake!


Why PyCharm? 

It is the platform I am using now to develop some base knowledge for AI, Image Processing, etc. One could use Visual Basic Community Edition.

Recently, I have published many posts on PyCharm in this blog. Search for PyCharm on this blog http://hodentekHelp.blogspot.com

Importing KIVY into PyCharm:

It is very easy as the library is already in PyCharm. However, for your project you need to install it before importing into Python code.

I created a project, PyWidgets and then searched here for KIVY as shown.


Just click on Install and then after installation click on Add Package. The library package will be added to the project. You can read and contact KIVY groups from this screen.


KIVY as stated earlier is not a standalone program but a library. To use this, you need a Python program into which you bring in this library.

In future posts the usage of this library will be described and discussed. It is an important part of multi-touch mobile app development.




Sunday, December 29, 2024

Would you like to watermark and protect your picture?

 You might have been shocked to see one of your pictures or image on someone else's site and felt betrayed. Chances are your name or reference is not even sited, just your image lifted from the internet. Watermarking is your protection against the plagiarism that happens sometimes.

What is watermarking?

Watermarking is the placing of a recognizable form of text or semi-transparent image on your picture so that if someone copies, your marking goes with the picture.

Here is an example of watermarking an image. You can shutterstock all over the image. You can copy from the site but it will have the watermarks.


Watermarking is more, it is branding

Watermarking a picture or an image is not just for protection, it is also your branding tool. Branding is an essential step you should take to be recognized on the internet and by far the most effective. Names like, Nike, Apple, Facebook are most recognizable because of branding. 

It is essential therefore that you take steps to establish your work by copywriting and watermarking.

Tools for watermarking:

There are many tools available for watermarking that are pretty cool. Here are just a few:

Watermarkly: A free, user-friendly tool for adding watermarks to photos

Canva: A free, online tool that lets you add a logo, name, or other visuals to your photos

PicMonkey: A free, online tool for adding watermarks to your images

Fotor: A free, online tool for adding watermarks to your images

Movavi Photo Editor: A free tool for making and editing collages

PhotoMarks: A tool for batch watermarking

Arclab Watermark Studio: A tool for adding multiple watermarks to images

Watermark Software: A tool for fast processing

Format Factory: A tool for watermarking photos and videos

uMark: A tool that uses barcodes and QR codes

This post shows you how to place a watermark on an image of your choosing using Python and an image library.

Python and image libraries have tools to do this. By extending the same concept, you can also watermark videos. I will be placing this text "Hodentek 2025" on the image shown below.


Here is the code in Python that allows you to create watermarks:

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

import os
from PIL import Image, ImageDraw, ImageFont

try:
# Open the original image
image_path = r"C:\Users\hoden\PycharmProjects\JNumpy\Jay.jpg"
original_image = Image.open(image_path)

# Create a watermark text
watermark_text = "Hodentek 2025"

# Create a new image for the watermark with an alpha layer (RGBA)
watermark_image = Image.new('RGBA', original_image.size, (0, 0, 0, 0))

# Get a drawing context
draw = ImageDraw.Draw(watermark_image)

# Define the font and size (you might need to adjust the font path)
font = ImageFont.truetype('arial.ttf', 72)

# Calculate the bounding box for the watermark text
bbox = draw.textbbox((0, 0), watermark_text, font=font)
text_width, text_height = bbox[2] - bbox[0], bbox[3] - bbox[1]
# position = (original_image.size[0] - text_width - 10, original_image.size[1] \
# - text_height - 10)
# Calculate the position for the watermark (center of the image)
position = ((original_image.size[0] - text_width) / 2, \
(original_image.size[1] - text_height) / 2)
# Draw the watermark text onto the watermark image
draw.text(position, watermark_text, fill=(255, 255, 255, 128), font=font)
# White text with transparency

# Combine the original image with the watermark
watermarked_image = Image.alpha_composite(original_image.convert('RGBA'), \
                                              watermark_image)

# Save and display the result
watermarked_image.show() # To display the image
watermarked_image.save('watermarked_output.png')

print('Watermarked image saved as watermarked_output.png')

except AttributeError as e:
print(f"Error: {e}")
print("Explanation:")
print("Make sure you are using the correct method and attributes.")

except OSError as e:
print(f"Error: {e}")
print("Explanation:")
print("This error likely occurs when the specified font file \
cannot be found or opened.")
print("Please double-check the font path and ensure the font \
file exists.")

except Exception as e:
print(f"An unexpected error occurred: {e}")

Note: Line continuation characters have been used, watch out.

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

 When you run this code, you will see the image with the watermark at its center  as shown:


Removing watermarks,? yes, Possible:

You may want to know also whether it is possible to remove watermarks. The answer is yes, you can remove watermarks with Python and the watermarked image, but it is more difficult and greater care is needed. Manual editing with Adobe Photoshop or GIMP is also possible. Presently there is an AI tool, Pixnova that removes watermark from photos and it can automatically remove watermark but preserving the original details. AI tools like Fotor and Vmake can help removing watermarks from videos as well.

Dynamic watermarking:

Yes, tools are available for this as well. Oh! you can hide watermarks also.


DynmaicWatermaking.jpg

Thursday, December 26, 2024

Ever Explored an Image? Dive In Now!


If you have not, it is time you do it. Python lends itself to be the way to unveil the magic behind images. While python is the main tool you need libraries to help along.

There is a famous adage, if you want to control something you need to measure it first. In order to change or use image in a yet to unknown ways, you need to unravel an image. Image processing is all about how in myriad ways you can use images for aesthetic, scientific and medical fields. Python with a plethora of image and other supportive libraries such as PIL, OpenCV, NumPy, etc. is great for this purpose. First of all we need to understand Pixel, it is like understanding a point in geometry, the fundamental building block.

What is a pixel?

The unveiling of an image starts with the building block of images, the pixels - geometrical structures with very minute dimensions that have some color in them.

Pixels are actually square. Each pixel is a tiny square of color that, when combined with other pixels, forms the images you see on screens. This grid of square pixels is what allows digital displays to render images with precision and clarity. The concept of pixels being square is fundamental to how digital images are created and displayed. In a sense, pixels are abstract that depend on the device on which we see the image. The physical size of a pixel is device dependent. The physical size of a pixel has to be derived from a knowledge of the resolving power of the device, the dots per inch seen on the device. While in Micro LEDs they are about 50 microns they can be fraction of a millimeter in large LEDs.  

Images are a grid of pixels, each with a specific color. When viewed together, these pixels form the images we see.

What is NumPy and what is its role in image processing?

In the process of understanding images, NumPy plays a crucial role. This library helps to separate an image into three distinct parts: height, width, and color. Furthermore, it isolates the colors red, green, and blue, placing them into their respective channels. By dismantling the image with NumPy, we can access the five important components of an image. These components can be manipulated using various image libraries in Python.

Also, while NumPy can disassemble an image, it can also reconstruct an image and it is extremely versatile. NumPy depends for its speed on the core C programming constructs but implemented for a high level language like Python.

Finding the height and width of an image using NumPy in Python:

This program takes in an image and find its shape with three arguments, height, width and number of channels. You can also see the result of running this code in PyCharm.

This image Kiss.jpg has height and width of 7401 and 7376 with three colors.

Finding the height, width and colors:

The following code unravels the image (the python program is using PyCharm interface):



1. When this code is run the image dimensions (height and width) are returned.

2. It separates the 3 color channels into its constituents.

3. It gives three images and saves them to a files in the same project

In arriving at these results it has,

1. Reduced the size of image by resizing so that final image is not distorted, visible and without any display related artifacts. (When this code was run without resizing, it returned 3 very large images all in grey).

2. After resizing, I have extracted the three channel information. Remember, it is zero-based.

3. Each channel (red, green, and blue) is populated by values from the image in a two-step process. In the first step, an array with the same dimensions as the image is created, but all elements are initialized to zero for the chosen channel. In the second step, this array is filled with the values of the pertinent color from the image.

4. It creates separate images of the same image in separate colors, one each for red, green and blue and shows them.

5. It also writes to file, the images for each of these channels.

As you can see, we have the height, width and three separate images of the image looking at ony red, green and blue values in its pixels.






Here is the code, should you try to run for your image:

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

import cv2
import numpy as np

# Load the image
image = cv2.imread(r'C:\Users\hoden\PycharmProjects\exploreImage\Images\TheKiss.jpg')
# Get the dimensions of the image
height, width, channels = image.shape

# Print the dimensions
print(f'Width: {width} pixels, Height: {height} pixels')

# resizing the image to display smaller sizes on my display device
resized_image = cv2.resize(image, (200, 200))

# Extract individual color channels
blue_channel = resized_image[:, :, 0]
green_channel = resized_image[:, :, 1]
red_channel = resized_image[:, :, 2]

# Create separate images for each channel
blue_image = np.zeros_like(resized_image)
blue_image[:, :, 0] = blue_channel

green_image = np.zeros_like(resized_image)
green_image[:, :, 1] = green_channel # Assign green channel to green image

red_image = np.zeros_like(resized_image)
red_image[:, :, 2] = red_channel

# Display the extracted channels as images
cv2.imshow('Blue Channel', blue_image)
cv2.imshow('Green Channel', green_image)
cv2.imshow('Red Channel', red_image)
cv2.waitKey(0)
cv2.destroyAllWindows()

# Save the extracted channels as images (optional)
cv2.imwrite('blue_channel.jpg', blue_image)
cv2.imwrite('green_channel.jpg', green_image)
cv2.imwrite('red_channel.jpg', red_image)



 

 





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.


Sunday, December 22, 2024

You have seen a GIF, have you created one?

  You have seen a GIF image and enjoyed it. But have you created one.? There are software programs to create GIFs and perhaps many online sites help creating GIFs.  Here is one for example, https://www.canva.com/create/gif-maker/. Animation akin to GIFS can also be created using javascript although there may not be resulting image with a .gif extension.

GIFs are like very small duration video clips but they are really a composite of many small images flipped rapidly, in-situ to create the illusion of motion. They are made to impress you by their motion.

Why GIFS?

Imagine bringing life to a still photo of a sunset by animating the clouds. An image may be worth a thousand words, but a GIF is worth a thousand images. It adds dynamic movement to static images, unleashing your creativity. If you're active on social media, GIFs are an invaluable tool for self-expression, offering endless possibilities. They bring humor, emotion, and laughter to any page, transforming a collection of static images into a vibrant and engaging experience. With GIFs, you can elevate your storytelling to new heights!"

Here is a simple GIF image copied from a web site  (display gif on web browser - Search):


Ins and outs of using Python to create GIFs:

GIF images have the .gif extension which stands for Graphics Interchange Format. 

In this post, I show you how to create from scratch a GIF using Python. Python uses a image library such as PIL to get the images into the program such as PyCharm. Once they are in the program, you need to use another library to do the flipping action. This library is called imageio, image input/output program. For GIFs this program takes in the images (a number of them) and then it customizes the duration each image is shown; whether the gif repeats itself and how many times it does, etc. Note: if you are new to PyCharm, read up my other Python/Image related posts in this blog, http://hodentekhelp.blogpost.com.

The program presented here also goes through the indexing of the images (as there are many images) which necessitate calling yet another useful library called NumPy. The imageio program cannot accept a image list, but a Numpy list and hence the use of the NumPy library.

In order to create a gif file in a python program, you need the following:

1. A set of images. 

2. Importing libraries PIL, ImageIO and Numpy.

Here is are some five image files I am using in the program:






These are not the best, but enough for the purpose.

Here is the python program that creates a GIF image taking in the images shown here:

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

BirdsGIF.py

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

# Import libraries used to create a GIF image

import imageio

import numpy as np

from PIL import Image

from PIL.ImageFile import ImageFile

# Load images

image1: ImageFile = Image.open(r'C:\Users\hoden\PycharmProjects\exploreImage\Images_3\Bird1.jpg')

image2 = Image.open(r'C:\Users\hoden\PycharmProjects\exploreImage\Images_3\Bird2.jpg')

image3 = Image.open(r'C:\Users\hoden\PycharmProjects\exploreImage\Images_3\Bird3.jpg')

image4 = Image.open(r'C:\Users\hoden\PycharmProjects\exploreImage\Images_3\Bird4.jpg')

image5 = Image.open(r'C:\Users\hoden\PycharmProjects\exploreImage\Images_3\Bird5.jpg')

# Resize images (optional)

image1 = image1.resize((200, 200))

image2 = image2.resize((200, 200))

image3 = image3.resize((200,200))

image4 = image4.resize((200,200))

image5 = image5.resize((200,200))

# Create list of images

images = [image1, image2, image3, image4, image5]

# Convert PIL image  list to NumPy arrays

images = [np.array(img) for img in images]

# Create the GIF using the image list

imageio.mimsave('my_animation.gif', images, duration=2000.0, loop=5)

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

The above program creates a image file with .gif extension and images show for 2000 milliseconds and the GIF image runs five times in succession. If you have time elapsed stills of any event you can easily turn it into an amazingly dynamic image.

That is all there is to creating a GIF. If your images are made with care and are of good quality you can indeed create a good GIF.

The GIf file created, my_animation.gif can be seen in Photo app on your windows computer device, however you can just drag and drop the image on a browser should also work.


Mahalo for staying with me. 

p.s: For these holidays, you can create your greeting card with a GIF. Try it!