Kristen
Kristen

Reputation: 19

2D convolution in python

I am taking a basic CS class and in it we have a project where we have to write a code for 2D convolution in python. I have placed the code I have written below:

def Convolve2D(image1, K, image2):
    #iterate over all rows (ignore 1-pixel borders) 
    for v in range(1, image2.getHeight()-1):
        graphics.update() # this updates the output for each row
        # for every row, iterate over all columns (again ignore 1-pixel borders)
        for u in range(1, image2.getWidth()-1):
            # for every pixel, iterate over region of overlap between
            #   input image and 3x3 kernel centered at current pixel
            for i in range (0, 3):
                for j in range (0, 3):                                                                                            
                    # compute output image pixel
                   image2.setPixel(u,v,graphics.color_rgb((image2.getPixel(u,v)[0] + image1.getPixel(u-1+i,v-1+j)[0]*K[i][j]),
                                    (image2.getPixel(u,v)[1] + image1.getPixel(u-1+i,v-1+j)[1]*K[i][j]), (image2.getPixel(u,v)[2]+image1.getPixel(u-1+i,v-1+j)[2]*K[i][j])))

for the last step I have to clamp and set the output image. By clamp I am being asked to use a clamp function that was previously defined as:

def Clamp(pix):
    pix = abs(pix)
    if pix > 255:
        pix = 255
    return pix

but I can't get this last step to work. Any advice would be appreciated.

Upvotes: 1

Views: 1228

Answers (1)

Ramchandra Apte
Ramchandra Apte

Reputation: 4079

As prelic said, then you are passing Clamp a string, when it needs a number.

Upvotes: 1

Related Questions