0% found this document useful (0 votes)
118 views9 pages

Python Basics for Image Processing Lab

This document provides an introduction to Python programming by covering various Python concepts like variables, data types, operators, conditional statements, loops, functions, and working with images using OpenCV. It discusses how to define and assign variables, perform arithmetic operations, use conditional statements like if-else and while loops, define and call functions, read and write images, and work with lists and slicing. Key concepts covered include using print() to output values, basic data types like integers, floats and strings, operators, boolean logic, basic list operations, functions with parameters and return values, and reading/displaying images using OpenCV.
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)
118 views9 pages

Python Basics for Image Processing Lab

This document provides an introduction to Python programming by covering various Python concepts like variables, data types, operators, conditional statements, loops, functions, and working with images using OpenCV. It discusses how to define and assign variables, perform arithmetic operations, use conditional statements like if-else and while loops, define and call functions, read and write images, and work with lists and slicing. Key concepts covered include using print() to output values, basic data types like integers, floats and strings, operators, boolean logic, basic list operations, functions with parameters and return values, and reading/displaying images using OpenCV.
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

LAB-01:Introduction to Python

OBJECTIVE:

To introduce students with python programming language.

1. # is used for commenting


# This is a comment.
2. Whatever you put inside parentheses of print function will be your output
print (5)
print (10)
print (12+6)
note: The print function automatically adds the new line character at the end
print (5, end=” ”)
print (“END”)
3. Operators
i. + plus
ii. - minus
iii. * multiply
iv. ** power
v. / divide
vi. // divide and floor
vii. % modulus
4. Variables
x=5
y, z = 3.14, 17.2 # right side is evaluated first and then assigned to left
side with corresponding values
print (x + y)
print(type(x)) # type () function returns the variable’s data type.
print(type(y))
z = True # here z is of class bool. True or False (first letter
capital)
The answer of equation containing one float is a float. The answer of / (divide)
operator is always float.

Page 1 of 9
print (type (10/2))
5. Strings
print (“hello world”)
print (‘hello world’) #both single and double quotes works same
print (“hello ‘world’ ”)
print (“hello \”world\” ”) #escape character( \ )
a=”py”
b=’charm’
print (a + b) # + will join the two strings
print (a, b)
print (a*5)
print (a + 5) # Type Error: must be str, not int
print (a + str (5)) # str ( ) function converts int or float to string
type
6. LISTS
x = [1,2,3,4]
note: list are not arrays because arrays are of single data type however list may
contain variables of different data types.
x=int (input (“Enter a number”) # input ( ) function always input string,
# int ( ) function is used to convert string to int
y = 3.14
z = "HELLO"
li = [x, y, z, 4]
print(li)
List indexes
# From left to right: 0  1  2
# From right to left: -1  -2  -3
print (li [2] [-4])
slicing
#list [start: end: optional step size] ; start is inclusive and end is exclusive
print (li [1:3])
print (li [Link])
print (li [:])
print (li [0:])

Page 2 of 9
print (li [:3])
print (li [2] [1:4])
#Deleting something from a list
del (li [2])

copy
w = [1, 2, 3, 4]
x=w # The assignment copies the reference to the original list
y = w [:] # Slicing creates a new list
x [0] = 6
y [1] = 9
print(w)
7. Indentation
Whitespace is important in Python. Actually, whitespace at the beginning of
the line is important. This is called indentation. Leading whitespace (spaces
and tabs) at the beginning of the logical line is used to determine the
indentation level of the logical line, which in turn is used to determine the
grouping of statements.
Try this.
x=2
if x==10:
print ("this is inside if block")
print ("this is also inside if block")
print("this will print always")

8. Boolean operations
 < (less than)
 (greater than)
 <= (less than or equal to)
 >= (greater than or equal to)
 == (equal to)
 ! = (not equal to)
 not (boolean NOT) if not x:
 and (boolean AND) if x==2 and y>4:
 or (boolean OR)

Page 3 of 9
9. The IF statement
number = 23
if number == 24:
print ('number is equal to 24')
elif number<24:
print (Number is less than 24)
else:
print (Number is higher than 24)

10. The while statements


number = 23
while number<50:
print(number)
number+=1
else:
print ("wow there is an else for while statement as well")

11. The for statement


#Indentation
for i in range (10):
if i==6:
break
print(i)
for i in range (3, 10):
print(i)
if i==6:
continue
for i in range (1, 10, 3):
print(i)

Page 4 of 9
12. Functions
def print_max (a, b=0):
if a > b:
print (a, 'is maximum')
elif a == b:
print (a, 'is equal to', b)
else:
print (b, 'is maximum')

print_max (3, 4)
x=5
y=7
print_max (x, y)
Keyword arguments
def func (a, b=5, c=10):
print ('a is', a, 'and b is', b, 'and c is', c)
func (3, 7)
func (25, c=24)
func (c=50, a=100)
Return
def max (x, y):
if x > y:
return x
else:
return y
m=max (3,5)
print(m)

Reading an Image:

Page 5 of 9
OpenCV (Open Source Computer Vision) is a computer vision library
that contains various functions to perform operations on pictures or
videos.
How to install:
[Link]
on-windows-using-anaconda-or-winpython-f24dd5c895eb
To read the images [Link]() method is used. This method loads
an image from the specified file. If the image cannot be read (because
of missing file, improper permissions, unsupported or invalid format)
then this method returns an empty matrix.

Syntax: [Link](path, flag)
Parameters:
path: A string representing the path of the image to be read.
flag: It specifies the way in which image should be read. It’s default value
is cv2.IMREAD_COLOR
Return Value: This method returns an image that is loaded from the
specified file.

cv2.IMREAD_COLOR: It specifies to load a color image. Any


transparency of image will be neglected. It is the default flag.
Alternatively, we can pass integer value 1 for this flag.
cv2.IMREAD_GRAYSCALE: It specifies to load an image in grayscale
mode. Alternatively, we can pass integer value 0 for this flag.

Page 6 of 9
# To read image from disk, we use
# [Link] function, in below method,
img = [Link]("[Link]", cv2.IMREAD_COLOR)

# Creating GUI window to display an image on screen


# first Parameter is windows title (should be in string format)
# Second Parameter is image array
[Link]("image", img)

# To hold the window on screen, we use [Link] method


# Once it detected the close input, it will release the control
# To the next line
# First Parameter is for holding screen for specified milliseconds
# It should be positive integer. If 0 pass an parameter, then it will
# hold the screen until user close it.
[Link](0)
 
# It is for removing/deleting created GUI window from screen
# and memory
[Link]()

[Link]() :method is used to save an image to any storage device. This


will save the image according to the specified format in current working
directory.
Syntax: [Link](filename, image)
Parameters:
filename: A string representing the file name. The filename must include
image format like .jpg, .png, etc.
image: It is the image that is to be saved.
Return Value: It returns true if image is saved successfully.

# Image path
image_path = r'C:\Users\old...’
  
# Image directory
directory = r'C:\Users\new....
  
# Using [Link]() method
# to read the image
img = [Link](image_path)
  
# Change the current directory 

Page 7 of 9
# to specified directory 
[Link](directory)
  
# List files and directories  
# in 'C:/Users/old’
print("Before saving image:")  
print([Link](directory))  
  
# Filename
filename = '[Link]'
  
# Using [Link]() method
# Saving the image
[Link](filename, img)
  
# List files and directories  
# in 'C:/Users / new’
print("After saving image:")  
print([Link](directory))
  
print('Successfully saved')

TASK 1:

x = [[1, 2, 3, 4, 5], [21, 22, 23, 24, 25], [31, 32, 33, 34, 35]]
 Write python code using python indexing and slicing for the following output.
Use only one print statement for each
i. [31, 32, 33, 34, 35]
ii. 23
iii. [22, 23]
iv. [1, 3, 5]
 Declare y = [0, 0, 0], now using for loop write average of first list in list ‘x’ on
first index of list y and so on. The print(y) should give the following output
o [3.0, 23.0, 33.0]

Page 8 of 9
TASK 2:

x = [1, 3, 5, 6, 7, 8, 6, 1, 2, 3]
y = [0, 0, 0, 0, 0, 0, 0, 0]
 Write python code using while loop that write average of first three items on
first index of y and so on. The print(y) should give the following output
o [3.0, 4.666666666666667, 6.0, 7.0, 7.0, 5.0, 3.0, 2.0]
 Define a function that takes list length as argument and returns the average.
Then calculate the average of x and y.

Task#3

Save our university logo from website and read it in grey scale and as colour
image. Show it in GUI. Then save it in different directory

Conclusion:
This lab gives a basic introductory session on the programming using python language.

Page 9 of 9

Common questions

Powered by AI

In Python, indentation is crucial because it defines the scope of code blocks within structures like if statements, for loops, and function definitions. Unlike some other languages that use braces or keywords to delimit blocks of code, Python uses indentation levels to indicate groupings. For example, in an if statement, both statements that are intended to execute only if the condition is true must be indented by the same level under the if clause. Incorrect indentation will result in a syntax error or logical errors because Python will misinterpret which statements belong together .

The cv2.imread() function in OpenCV is used to read images from the disk into a program. It can be configured through the 'flag' parameter to load images in different modes. The default mode is cv2.IMREAD_COLOR, which loads a color image while ignoring any transparency. Alternatively, cv2.IMREAD_GRAYSCALE can be used to load the image in grayscale. The function returns an image if successful, otherwise, it returns an empty matrix if the image cannot be read due to issues like a missing file or unsupported format .

In Python, the '/' operator performs true division, which means it always returns a float, regardless of the operands' types. For example, 10/3 results in 3.333... The '//' operator, known as floor division, divides and returns the largest integer less than or equal to the quotient, effectively removing the fractional part. Thus, 10//3 results in 3. The choice between these operators affects precision and can be critical in applications requiring integer results or consistent float precision .

cv2.imwrite() is essential in image processing as it allows saving images to disk in various formats. This function requires the file name and the image data to be written. While cv2.imread() is used to load and read images from disk, cv2.imwrite() is its counterpart, used to store processed images back to a storage device, effectively enabling both input and output operations in image processing workflows. cv2.imwrite() returns true upon successful storage, facilitating seamless integration of image read-modify-save tasks .

Python's logical operators 'and' and 'or' are used to combine boolean expressions. The 'and' operator evaluates as True if both operands are True, returning the second operand if both are True, and the first falsy value if any operand is False. The 'or' operator evaluates as True if at least one operand is True, returning the first truthy operand it encounters, and defaults to the last operand if all are False. These operators adhere to short-circuiting, stopping evaluation as soon as the result is determinable, optimizing execution .

In Python, string concatenation is performed using the '+' operator, which joins two or more strings together. For example, 'a' + 'b' would result in 'ab'. However, using '+' to combine a string with a non-string type, such as an integer, results in a TypeError unless the non-string type is explicitly converted to a string. For instance, trying to concatenate 'a' + 5 would raise an error, whereas 'a' + str(5) would correctly produce 'a5' .

OpenCV's cv2.imshow() function is used to display images in a window, where the first parameter is the window title and the second is the image array. cv2.waitKey(), when called after cv2.imshow(), serves to hold the window open, waiting for user input. The parameter for cv2.waitKey() determines how long the window stays open, with '0' meaning it waits indefinitely for a keystroke to close, thus giving the user control over the display duration. Together, these functions facilitate interactive image viewing within applications .

List slicing in Python allows you to access a sub-list or a range of elements from a list using the syntax list[start:end:step]. The start index is inclusive, while the end index is exclusive, and the step is optional. For example, given the list li = [1, 2, 3, 4, 5], the slice li[1:4] would return [2, 3, 4] as it starts from index 1 up to, but not including, index 4. List slicing is a powerful tool for accessing and manipulating subsets of data in a list .

The 'for' statement in Python is used to iterate over a sequence, such as a list, tuple, or string, executing a block of code for each element. For example, 'for i in range(3, 10):' iterates numbers from 3 to 9. The 'break' and 'continue' statements modify loop behavior: 'break' exits the loop prematurely, while 'continue' skips the current iteration and moves to the next. These allow for precise control over loop execution, enabling tasks such as filtering iteration sequences or aborting processes based on conditions .

In Python, variables are dynamically typed, meaning that you can assign values of any data type to a variable without specifying the type explicitly. Python determines the data type based on the value assigned. When you change the value or type of a variable, Python will update the variable's type to reflect the new value. For instance, if you initially assign an integer to a variable (x=5) and later assign a string to the same variable (x='hello'), the type is updated accordingly. This flexibility is part of Python's dynamic typing system, allowing seamless reassignments but requiring careful management to avoid type-related errors .

You might also like