0% found this document useful (0 votes)
19 views

Week 10

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

Week 10

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

Q1.

from PIL import Image, ImageFilter

import numpy as np

from scipy.signal import convolve2d

class ImageProcessor:

def __init__(self, image_path):

# Open imgage

self.img = Image.open(image_path)

def image_process(self, output_path, blur_radius=0):

# Convert image to grayscale and apply Gaussian blur

img = self.img.convert('L')

img = img.filter(ImageFilter.GaussianBlur(blur_radius))

img_array = np.array(img)

# Sobel kernels for edge detection

sobel_x = np.array([[-1, 0, 1],

[-2, 0, 2],

[-1, 0, 1]])

sobel_y = np.array([[-1, -2, -1],

[0, 0, 0],

[1, 2, 1]])

# Convolve image with Sobel kernels to compute gradients

gradx = convolve2d(img_array, sobel_x)

grady = convolve2d(img_array, sobel_y)


# Check if convolution was successful

if gradx is None or grady is None:

print("Error: Unable to process image.")

return

# Compute gradient magnitude

grad_mag = np.sqrt(gradx**2 + grady**2)

max_gradient = np.max(grad_mag)

# Check if max gradient is zero

if max_gradient == 0:

print("Error: Unable to process image. Max gradient is zero.")

return

# Normalize gradient magnitude to range [0, 255]

grad_mag = (

255.0 / np.max(grad_mag)) * grad_mag

grad_mag_scaled = grad_mag * \

(255.0 / np.max(grad_mag))

# Convert gradient magnitude array to PIL Image

edge_image = Image.fromarray(

grad_mag_scaled.astype(np.uint8))

# Save the edge-detected image

edge_image.save(output_path)

# Example usage

img = ImageProcessor("small.jpg")

img.image_process("s.jpg", 1)
OUTPUT:

Q2.

import turtle

class Draw: # turtle class for drawing

def __init__(self, turtle, screen): # init turtle attributes


self.turtle = turtle

self.screen = screen

self.turtle.speed(0)

self.turtle.hideturtle()

self.turtle.pensize(1.5)

self.screen.tracer(0)

# function for rectangle

def rectangle(self, sidex, sidey, coords=None, angle=0):

a = self.turtle

if coords is None: # if no position is given

coords = a.position() # use current position

# move turtle to correct positoin for rectangle in center

a.setheading(angle)

a.up()

a.goto(coords)

a.bk(sidex/2)

a.right(90)

a.bk(sidey/2)

a.left(90)

a.pendown()

# draw rectangle

a.fillcolor("cyan" if sidex==sidey else "red")

a.begin_fill()

for i in range(2):

a.forward(sidex)

a.right(90)

a.forward(sidey)

a.right(90)

a.end_fill()

# function to draw circle


def circle(self, radius, coords=None):

t = self.turtle

if coords is None: # if no position is given

coords = t.position() # use current position

# draw from center and return to center

t.up()

t.goto(coords)

t.right(90)

t.fd(radius)

t.left(90)

t.down()

t.fillcolor("green")

t.begin_fill()

t.circle(radius)

t.end_fill()

t.up()

t.goto(coords)

# function for drawing lines

def triangle(self, side_len, coords, angle=0):

t = self.turtle

t.up()

t.goto(coords)

t.down()

t.seth(angle)

t.fillcolor("purple")

t.begin_fill()

for i in range(3):

t.fd(side_len)

t.left(120)

t.end_fill()
# function for drawing the robot

def draw_robot(self):

self.rectangle(200,200)

self.rectangle(50,100,(-50,-150))

self.rectangle(50,100,(50,-150))

self.rectangle(60,60,(-50,-230))

self.rectangle(60,60,(50,-230))

self.rectangle(35,40,(0,120))

self.circle(80,(0,220))

self.rectangle(70,30,(0,180))

self.circle(20,(-30,240))

self.circle(20,(30,240))

self.triangle(60,(101,105),-90)

self.triangle(60,(-101,105),-150)

self.triangle(60,(-30,295))

self.triangle(60,(75,250),-90)

self.triangle(60,(-75,250),-150)

self.rectangle(45,100,(152,15),30)

self.rectangle(45,100,(-152,15),-30)

self.circle(20,(188,-45))

self.circle(20,(-188,-45))

self.screen.update()

t = turtle.Turtle()

screen = turtle.Screen()

screen.setup(width=700,height=700)

d = Draw(t, screen) # class instance

d.draw_robot() # draw shape

screen.exitonclick()
Output:

Q3.

class Calsi:

def expression_split(self, expression):

expression = expression.replace(" ", "") # remove space

operators = {'+': 1, '-': 1, '*': 2, '/': 2, '^': 3}

output = []
list2 = []

i=0

while i < len(expression):

if expression[i].isdigit():

num = ''

while i < len(expression) and expression[i].isdigit():

num += expression[i]

i += 1

output.append(num)

elif expression[i] in operators:

while (list2 and list2[-1] in operators

and operators[list2[-1]] >= operators[expression[i]]):

output.append(list2.pop())

list2.append(expression[i])

i += 1

elif expression[i] == '(':

list2.append(expression[i])

i += 1

elif expression[i] == ')':

while list2 and list2[-1] != '(':

output.append(list2.pop())

if list2[-1] == '(':

list2.pop() # Remove '('

i += 1

while list2:

output.append(list2.pop())

return output
def calculate(self, expression):

list3 = []

for token in expression:

if token.isdigit():

list3.append(int(token))

else:

num2 = list3.pop()

num1 = list3.pop()

if token == '+':

list3.append(num1 + num2)

elif token == '-':

list3.append(num1 - num2)

elif token == '*':

list3.append(num1 * num2)

elif token == '/':

list3.append(num1 / num2)

elif token == '^':

list3.append(num1 ** num2)

return list3[0]

# Example usage:

expression = input("enter a expression: ")

d = Calsi()

k = d.expression_split(expression)

result = d.calculate(k)

print(f"Result of '{expression}' is: {result}")

Output:

You might also like