0% found this document useful (0 votes)
17 views8 pages

Python Ans S6

The document discusses various Python libraries for image processing, including OpenCV, Pillow, and scikit-image. It also covers attributes and methods of the turtle module for controlling turtle graphics, along with example Python code for converting images to black and white, drawing shapes, and creating a temperature conversion GUI using Tkinter. Additionally, it provides detailed explanations of the functions and methods used in the examples.

Uploaded by

Gauri S
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views8 pages

Python Ans S6

The document discusses various Python libraries for image processing, including OpenCV, Pillow, and scikit-image. It also covers attributes and methods of the turtle module for controlling turtle graphics, along with example Python code for converting images to black and white, drawing shapes, and creating a temperature conversion GUI using Tkinter. Additionally, it provides detailed explanations of the functions and methods used in the examples.

Uploaded by

Gauri S
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 8

List any three Image Processing Python libraries.

 OpenCV (cv2) – A powerful library for real-time image processing, computer vision, and
machine learning applications. It supports operations like filtering, edge detection, object
recognition, and more.
 Pillow (PIL) – A lightweight and easy-to-use library for opening, manipulating, and
saving images in different formats (JPEG, PNG, BMP, etc.).
 scikit-image – A collection of image processing tools built on top of SciPy and NumPy,
useful for tasks like segmentation, feature extraction, and image transformations.

Turtle attributes:
In Python's turtle module, there are several attributes and methods you can use to control
the turtle's behavior and appearance. Some of the key attributes include:
1. Position and Orientation:
o xcor() – Returns the turtle's x-coordinate.
o ycor() – Returns the turtle's y-coordinate.
o heading() – Returns the current angle of the turtle.
2. Pen Attributes:
o pen() – Toggles between drawing and not drawing.
o pendown() – Puts the pen down to start drawing.
o penup() – Lifts the pen so that no drawing happens.
o pensize(width) – Sets the width of the pen.
o pencolor(color) – Sets the pen color.
o fillcolor(color) – Sets the color used for filling shapes.
o color(pencolor, fillcolor) – Sets both pen and fill colors.
3. Appearance Attributes:
o shape(shape) – Sets the shape of the turtle (e.g., "turtle", "circle", "square").
o shapesize(stretch_wid, stretch_len, outline) – Stretches the turtle shape.
o color(color) – Sets the color of the turtle.
o turtlesize(stretch_wid, stretch_len, outline) – Adjusts the turtle's size.
4. Speed and Motion:
o speed(speed) – Sets the speed of the turtle (0 for the fastest, 10 for slowest).
o towards(x, y) – Returns the angle between the turtle and a point (x, y).
o setposition(x, y) – Moves the turtle to a specific location.
5. State Attributes:
o isdown() – Returns True if the pen is down (drawing).
o isvisible() – Returns True if the turtle is visible.
o showturtle() – Makes the turtle visible.
o hideturtle() – Hides the turtle.
6. Screen Attributes:
o bgcolor(color) – Sets the background color of the screen.
o screensize(width, height) – Sets the screen size.
o title(name) – Sets the title of the turtle graphics window.
These attributes are used to control the turtle's position, movement, appearance, and more.

Write a Python function to convert an image to black and white using Image Processing
methods.
from PIL import Image

def convert_to_black_and_white_pil(image_path, output_path):


# Open an image
img = Image.open(image_path)

# Convert image to grayscale


gray_img = img.convert("L")

# Convert grayscale to pure black and white


bw_img = gray_img.point(lambda x: 0 if x < 128 else 255, '1')

# Save the image


bw_img.save(output_path)
print("Black and white image saved successfully.")

# Example usage
convert_to_black_and_white_pil("input.jpg", "output_bw.jpg")

Here is a simple Python program that uses the turtle module to draw a circle and fill it with
red color.
Python Program:
import turtle

# Create a turtle object


t = turtle.Turtle()

# Set fill color to red


t.fillcolor("red")

# Start filling the shape


t.begin_fill()

# Draw a circle with radius 100


t.circle(100)

# End filling the shape


t.end_fill()

# Hide the turtle


t.hideturtle()

# Keep the window open


turtle.done()
Explanation of Turtle Methods Used:
1. turtle.Turtle()
o Creates a turtle object (t in this case) that can be used to draw shapes.
2. t.fillcolor("red")
o Sets the fill color to red. This does not start the filling but defines the color.
3. t.begin_fill()
o Indicates that the filling process should start. Any shape drawn after this call
will be filled with the specified color.
4. t.circle(100)
o Draws a circle with a radius of 100 units.
5. t.end_fill()
o Stops the filling process and fills the shape with the specified color.
6. t.hideturtle()
o Hides the turtle pointer to make the drawing look cleaner.
7. turtle.done()
o Ensures that the window remains open after drawing is completed.

image with a caption: You can use the tkinter module along with PIL (Pillow) to create a
GUI that displays an image with a caption.
Python Code:
import tkinter as tk
from PIL import Image, ImageTk

# Create main window


root = tk.Tk()
root.title("Image with Caption")

# Load the image


image_path = "your_image.jpg" # Replace with your image file path
image = Image.open(image_path)
image = image.resize((300, 300)) # Resize image if needed
photo = ImageTk.PhotoImage(image)

# Create a label to display the image


image_label = tk.Label(root, image=photo)
image_label.pack(pady=10)

# Create a caption label


caption_label = tk.Label(root, text="This is a sample caption.", font=("Arial", 14), fg="blue")
caption_label.pack()

# Run the GUI event loop


root.mainloop()

Explanation:
1. tk.Tk() - Creates the main application window.
2. PIL.Image.open(image_path) - Opens the image file.
3. image.resize((300, 300)) - Resizes the image to fit the GUI window.
4. ImageTk.PhotoImage(image) - Converts the image for use in Tkinter.
5. tk.Label(root, image=photo) - Displays the image in the GUI.
6. tk.Label(root, text="This is a sample caption.", font=("Arial", 14), fg="blue") -
Displays a caption below the image.
7. pack() - Arranges widgets in the window.
8. root.mainloop() - Starts the GUI event loop.
💡 Note: Replace "your_image.jpg" with the actual path of your image file.

The speed() method in the turtle module is used to control the drawing speed of the turtle.
t.speed(speed_value)
Where speed_value can be an integer from 0 to 10 or a string.

Speed Levels and Their Effects


Speed Value Description
0 Fastest speed (no animation, instant drawing)
1 Slowest speed
3 Slow speed
6 Normal speed (default)
10 Fastest speed with animation
Example Usage
import turtle

t = turtle.Turtle()

t.speed(1) # Very slow speed


t.forward(100)

t.speed(10) # Very fast speed


t.forward(100)

turtle.done()

Temperature conversion

import tkinter as tk

# Function to convert Celsius to Fahrenheit


def celsius_to_fahrenheit():
try:
celsius = float(celsius_entry.get()) # Get Celsius input
fahrenheit = (celsius * 9/5) + 32 # Convert to Fahrenheit
fahrenheit_entry.delete(0, tk.END) # Clear Fahrenheit entry
fahrenheit_entry.insert(0, str(fahrenheit)) # Display result in Fahrenheit entry
except ValueError:
fahrenheit_entry.delete(0, tk.END) # Clear entry if invalid input

# Function to convert Fahrenheit to Celsius


def fahrenheit_to_celsius():
try:
fahrenheit = float(fahrenheit_entry.get()) # Get Fahrenheit input
celsius = (fahrenheit - 32) * 5/9 # Convert to Celsius
celsius_entry.delete(0, tk.END) # Clear Celsius entry
celsius_entry.insert(0, str(celsius)) # Display result in Celsius entry
except ValueError:
celsius_entry.delete(0, tk.END) # Clear entry if invalid input

# Create the main window


window = tk.Tk()
window.title("Temperature Converter")

# Set initial values


celsius_entry = tk.Entry(window, width=20)
celsius_entry.grid(row=0, column=1)
celsius_entry.insert(0, "0.0") # Initial value set to 0.0

fahrenheit_entry = tk.Entry(window, width=20)


fahrenheit_entry.grid(row=1, column=1)
fahrenheit_entry.insert(0, "0.0") # Initial value set to 0.0

# Labels
celsius_label = tk.Label(window, text="Celsius:")
celsius_label.grid(row=0, column=0)

fahrenheit_label = tk.Label(window, text="Fahrenheit:")


fahrenheit_label.grid(row=1, column=0)

# Buttons
c_to_f_button = tk.Button(window, text="C to F", command=celsius_to_fahrenheit)
c_to_f_button.grid(row=2, column=0)

f_to_c_button = tk.Button(window, text="F to C", command=fahrenheit_to_celsius)


f_to_c_button.grid(row=2, column=1)

# Run the GUI loop


window.mainloop()

Detailed description of each part of the Python program using tkinter for creating a
temperature converter GUI:
1. Importing Tkinter:
import tkinter as tk
 This line imports the tkinter module, which is used to create graphical user interfaces
(GUIs) in Python. The tk is an alias for tkinter, making it easier to reference the
module throughout the program.
2. Function to Convert Celsius to Fahrenheit:
def celsius_to_fahrenheit():
try:
celsius = float(celsius_entry.get()) # Get Celsius input
fahrenheit = (celsius * 9/5) + 32 # Convert to Fahrenheit
fahrenheit_entry.delete(0, tk.END) # Clear Fahrenheit entry
fahrenheit_entry.insert(0, str(fahrenheit)) # Display result in Fahrenheit entry
except ValueError:
fahrenheit_entry.delete(0, tk.END) # Clear entry if invalid input
 def celsius_to_fahrenheit():: This defines a function named celsius_to_fahrenheit
that will convert the temperature from Celsius to Fahrenheit.
 celsius = float(celsius_entry.get()): This line retrieves the value from the
celsius_entry text field, which contains the Celsius temperature, and converts it to a
float.
 fahrenheit = (celsius * 9/5) + 32: This performs the conversion from Celsius to
Fahrenheit using the formula: F=(C×95)+32F = (C \times \frac{9}{5}) + 32.
 fahrenheit_entry.delete(0, tk.END): This clears the fahrenheit_entry field, removing
any previously entered or calculated values.
 fahrenheit_entry.insert(0, str(fahrenheit)): This inserts the calculated Fahrenheit
temperature into the fahrenheit_entry field as a string.
 except ValueError:: If there is an error (e.g., the user enters non-numeric values),
this block will execute.
 fahrenheit_entry.delete(0, tk.END): If an error occurs, it clears the fahrenheit_entry
field to reset it.
3. Function to Convert Fahrenheit to Celsius:
def fahrenheit_to_celsius():
try:
fahrenheit = float(fahrenheit_entry.get()) # Get Fahrenheit input
celsius = (fahrenheit - 32) * 5/9 # Convert to Celsius
celsius_entry.delete(0, tk.END) # Clear Celsius entry
celsius_entry.insert(0, str(celsius)) # Display result in Celsius entry
except ValueError:
celsius_entry.delete(0, tk.END) # Clear entry if invalid input
 def fahrenheit_to_celsius():: This defines a function named fahrenheit_to_celsius
to convert Fahrenheit to Celsius.
 fahrenheit = float(fahrenheit_entry.get()): Retrieves the value from the
fahrenheit_entry text field and converts it to a float.
 celsius = (fahrenheit - 32) * 5/9: Converts the Fahrenheit value to Celsius using the
formula: C=(F−32)×59C = (F - 32) \times \frac{5}{9}.
 celsius_entry.delete(0, tk.END): Clears the celsius_entry field to prepare for
displaying the new result.
 celsius_entry.insert(0, str(celsius)): Inserts the calculated Celsius value into the
celsius_entry field as a string.
 except ValueError:: Handles errors (if the input is not a valid number).
 celsius_entry.delete(0, tk.END): Clears the celsius_entry field if the input is invalid.
4. Creating the Main Window:
window = tk.Tk()
window.title("Temperature Converter")
 window = tk.Tk(): This creates the main window for the application. Tk() is a
constructor that initializes the root window where all widgets will be placed.
 window.title("Temperature Converter"): Sets the title of the main window to
"Temperature Converter".
5. Setting Initial Values for Entry Widgets:
celsius_entry = tk.Entry(window, width=20)
celsius_entry.grid(row=0, column=1)
celsius_entry.insert(0, "0.0") # Initial value set to 0.0

fahrenheit_entry = tk.Entry(window, width=20)


fahrenheit_entry.grid(row=1, column=1)
fahrenheit_entry.insert(0, "0.0") # Initial value set to 0.0
 celsius_entry = tk.Entry(window, width=20): Creates an Entry widget for the
Celsius input, with a width of 20 characters.
 celsius_entry.grid(row=0, column=1): Places the celsius_entry widget in the first
row and second column of a grid layout.
 celsius_entry.insert(0, "0.0"): Inserts the initial value "0.0" into the Celsius entry
field.
 fahrenheit_entry = tk.Entry(window, width=20): Creates a similar Entry widget for
the Fahrenheit input.
 fahrenheit_entry.grid(row=1, column=1): Places the Fahrenheit entry field in the
second row and second column.
 fahrenheit_entry.insert(0, "0.0"): Sets the initial value of the Fahrenheit entry field
to "0.0".
6. Creating Labels for Celsius and Fahrenheit:
celsius_label = tk.Label(window, text="Celsius:")
celsius_label.grid(row=0, column=0)

fahrenheit_label = tk.Label(window, text="Fahrenheit:")


fahrenheit_label.grid(row=1, column=0)
 celsius_label = tk.Label(window, text="Celsius:"): Creates a Label widget for the
Celsius label, which displays the text "Celsius:".
 celsius_label.grid(row=0, column=0): Places the label in the first row and first
column.
 fahrenheit_label = tk.Label(window, text="Fahrenheit:"): Creates a Label widget
for the Fahrenheit label, which displays the text "Fahrenheit:".
 fahrenheit_label.grid(row=1, column=0): Places the label in the second row and
first column.
7. Creating Buttons for Conversion:
c_to_f_button = tk.Button(window, text="C to F", command=celsius_to_fahrenheit)
c_to_f_button.grid(row=2, column=0)

f_to_c_button = tk.Button(window, text="F to C", command=fahrenheit_to_celsius)


f_to_c_button.grid(row=2, column=1)
 c_to_f_button = tk.Button(window, text="C to F",
command=celsius_to_fahrenheit): Creates a button labeled "C to F". When this
button is clicked, it calls the celsius_to_fahrenheit function.
 c_to_f_button.grid(row=2, column=0): Places the "C to F" button in the third row
and first column.
 f_to_c_button = tk.Button(window, text="F to C",
command=fahrenheit_to_celsius): Creates another button labeled "F to C". This
button triggers the fahrenheit_to_celsius function when clicked.
 f_to_c_button.grid(row=2, column=1): Places the "F to C" button in the third row
and second column.
8. Running the Main Loop:
window.mainloop()
 window.mainloop(): This starts the Tkinter event loop, which waits for user
interactions (like button clicks or text input) and updates the GUI accordingly. The
program will keep running until the user closes the window.
Summary of the Program:
 This program creates a simple GUI with Tkinter to convert temperatures between
Celsius and Fahrenheit.
 There are two input fields: one for Celsius and one for Fahrenheit.
 The program has two buttons: one to convert from Celsius to Fahrenheit, and
another to convert from Fahrenheit to Celsius.
 The initial values for both fields are set to 0.0.
 When the user enters a value and clicks a button, the corresponding conversion is
performed and displayed in the other field. If invalid input is entered, the fields are
cleared.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy