Search code examples
pythonimage-processingpython-imaging-libraryimagefilter

How to start this python image filter?


am a python noob here. I was working on a project for my class, in which we had to make an image filter. I was able to get the two filters that are currently there (pixelate and add/remove colour) working separately, but when used together, they only both show if the pixelization is done before changing the colours. Is there a way to make it so that they will both show in the end, no matter the order they are called? my code is below:

#####################################
#    Your Filters with User Input   #
#####################################

def filter2():
  print("Code for filter2")

  addr = int(input("How much red would you like to add to the image (between -255 and 255)? "))
  addg = int(input("How much green would you like to add to the image (between -255 and 255)? "))
  addb = int(input("How much blue would you like to add to the image (between -255 and 255)? "))

  pixels = img.getdata()
 
  new_pixels = []
  
  for p in pixels:
    new_pixels.append(p)
  
  location = 0
  
  while location < len(new_pixels):
   
    p = new_pixels[location]
      
    r = p[0]
    g = p[1]
    b = p[2]
      
    newr = r + addr
    newg = g + addg
    newb = b + addb
      
    new_pixels[location] = (newr, newg, newb)
      
    location = location + 1
 
  newImage = Image.new("RGB", img.size)
  
  newImage.putdata(new_pixels)

  return newImage

def filter3():
  print("Code for filter3")
  img = Image.open('image.jpg')
  setting = input("How much pixelization would you like (low, medium, or high)? ")

  if (setting == "low"):
    imgSmall = img.resize((128,128),resample=Image.BILINEAR)
    newImage = imgSmall.resize(img.size,Image.NEAREST)

  elif (setting == "medium"):
    imgSmall = img.resize((64,64),resample=Image.BILINEAR)
    newImage = imgSmall.resize(img.size,Image.NEAREST)

  elif (setting == "high"):
    imgSmall = img.resize((32,32),resample=Image.BILINEAR)
    newImage = imgSmall.resize(img.size,Image.NEAREST)

  else:
    print("Invalid setting")

  return newImage

# Creates the four filter images and saves them to our files
a = grey()
a.save("grey.jpg")
b = filter1()
b.save("filter1.jpg")
c = filter2()
c.save("filter2.jpg")
d = filter3()
d.save("filter3.jpg")


# Create the combined filter image and saves it to our files

img.save("combinedFilters.jpg")

I have been working on this for the longest, and any help to solving my problem would be greatly appreciated.

Edit: this was the smallest I was able to reduce the code to, while keeping an idea of what it is supposed to do.


Solution

  • I got it to work as intended, I just had to remove the line that said "img = Image.open('image.jpg')" from the "filter3" function.