Jannieel
Jannieel

Reputation: 11

How does one invert an area of an image with python?

I was prompted to modify one of our filters so that we can specify which portion of the image should be modified. row1 and col1 : the top left coordinates the rectangle to modify row2 and col2: the bottom right coordinates of the rectangle to modify

I have attmepted this but it has not worked.

This is what I have attempted thus far

`

def invertspot(pic, row1, col1, row2, col2):
      # Go through each row and column
      for row in range(pic.height):
        for col in range(pic.width):
          # Gets a pixel at row/col
          pixel = pic.pixels[row1][col1][row2][col2]

          # Get the RGB values of this pixel
          red = pixel.red
          green = pixel.green
          blue = pixel.blue
          # Resave them and get the inverse by subtracting 255 from the value of the
          #color
          pixel.red = 255 - red
          pixel.green = 255 - green
          pixel.blue = 255 - blue

          # Finally, reset the pixel stored at that spot
          pic.pixels[row][col] = pixel

`

Upvotes: 1

Views: 211

Answers (2)

Mark Setchell
Mark Setchell

Reputation: 207465

Sticking just with PIL, you can do that like this:

#!/usr/bin/env python3

from PIL import Image, ImageChops

# Open image
im = Image.open('artistic-swirl.jpg')

# Define bounding box (left, upper, right, lower)
bbox = (100, 150, 300, 350)

# Extract the ROI, invert it and paste it back
ROI = im.crop(bbox)
ROI = ImageChops.invert(ROI)
im.paste(ROI, bbox)
im.save('result.png')

Which turns this:

enter image description here

into this:

enter image description here

Upvotes: 2

Nick ODell
Nick ODell

Reputation: 25220

I would do this in numpy. Easier and runs faster.

from PIL import Image
import numpy as np

img = Image.open("test186_img.jpg")

def invertspot(pic, row1, col1, row2, col2):
    array = np.array(img)
    subset = array[row1:row2, col1:col2]
    subset = 255 - subset
    array[row1:row2, col1:col2] = subset
    return Image.fromarray(array)
invertspot(img, 200, 600, 500, 800)

Example output:

lion with inverted patch

(Image credit: Wikipedia)

Upvotes: 2

Related Questions