Search code examples
pythonpython-3.xcimage

Python-3, my program doesn't show a negative image


So I need to follow the function in my textbook, to make an image negative and show the negative image. I've tried changing a few things in to replicate the previous function see to if that would change anything like typing in what image I want to have a negative of. It compiles and runs fine showing no errors it just doesn't show me a negative of my image, so I don't know whats the issue.

from cImage import *
def negativePixel(oldPixel):
    newRed = 255 - oldPixel.getRed()
    newGreen = 255 - oldPixel.getGreen()
    newBlue = 255 - oldPixel.getBlue()
    newPixel = Pixel(newRed, newGreen, newBlue)
    return newPixel`



def MakeNegative(imageFile):
    oldImage = FileImage(imageFile)
    width = oldImage.getWidth()
    height = oldImage.getHeight()

    myImageWindow = ImageWin("Negative Image", width * 2, height)
    oldImage.draw(myImageWindow)
    newIn = EmptyImage(width, height)

    for row in range(height):
        for col in range(width):
            oldPixel = oldImage.getPixel(col, row)
            newPixel = negativePixel(oldPixel)
            newIn.setPixel(col, row, newPixel)
newIn.setPosition(width + 1, 0)
newIn.draw(myImageWindow)
myImageWindow.exitOnClick()

Solution

  • Your code wasn't compiling or running for me; I fixed a few things - indentation, import image (not cImage), not invoking MakeNegative(), parameters out of order, etc. This works for me. I'm on Ubuntu 18.04, Python 3.6.9, cImage-2.0.2, Pillow-7.2.0.

    from image import *
    def negativePixel(oldPixel):
        newRed = 255 - oldPixel.getRed()
        newGreen = 255 - oldPixel.getGreen()
        newBlue = 255 - oldPixel.getBlue()
        newPixel = Pixel(newRed, newGreen, newBlue)
        return newPixel
    
    
    
    def MakeNegative(imageFile):
        oldImage = FileImage(imageFile)
        width = oldImage.getWidth()
        height = oldImage.getHeight()
    
        myImageWindow = ImageWin(width * 2, height, "Negative Image")
        oldImage.draw(myImageWindow)
        newIn = EmptyImage(width, height)
    
        for row in range(height):
            for col in range(width):
                oldPixel = oldImage.getPixel(col, row)
                newPixel = negativePixel(oldPixel)
                newIn.setPixel(col, row, newPixel)
    
        newIn.setPosition(width + 1, 0)
        newIn.draw(myImageWindow)
        myImageWindow.exitOnClick()
    
    MakeNegative('Lenna_test_image.png')
    

    enter image description here