Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Digital Image cropping in Python

Got this question from a professor, a physicist.

I am a beginner in Python programming. I am not a computer professional I am a physicist. I was trying to write a code in python for my own research which involves a little image processing.

All I need to do is to display an image and then select a region of interest using my mouse and finally crop out the selected region. I can do this in Matlab using the ginput() function.

I tried using PIL. But I find that after I issue the command Image.show(), the image is displayed but then the program halts there unless I exit from the image window. Is there any way to implement what I was planning. Do I need to download any other module? Please advise.

like image 990
lprsd Avatar asked Dec 09 '22 21:12

lprsd


1 Answers

While I agree with David that you should probably just use GIMP or some other image manipulation program, here is a script (as I took it to be an exercise to the reader) using pygame that does what you want. You will need to install pygame as well as the PIL, usage would be:

scriptname.py <input_path> <output_path>

Actual script:

import pygame, sys
from PIL import Image
pygame.init()

def displayImage( screen, px, topleft):
    screen.blit(px, px.get_rect())
    if topleft:
        pygame.draw.rect( screen, (128,128,128), pygame.Rect(topleft[0], topleft[1], pygame.mouse.get_pos()[0] - topleft[0], pygame.mouse.get_pos()[1] - topleft[1]))
    pygame.display.flip()

def setup(path):
    px = pygame.image.load(path)
    screen = pygame.display.set_mode( px.get_rect()[2:] )
    screen.blit(px, px.get_rect())
    pygame.display.flip()
    return screen, px

def mainLoop(screen, px):
    topleft = None
    bottomright = None
    runProgram = True
    while runProgram:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                runProgram = False
            elif event.type == pygame.MOUSEBUTTONUP:
                if not topleft:
                    topleft = event.pos
                else:
                    bottomright = event.pos
                    runProgram = False
        displayImage(screen, px, topleft)
    return ( topleft + bottomright )


if __name__ == "__main__":
    screen, px = setup(sys.argv[1])
    left, upper, right, lower = mainLoop(screen, px)
    im = Image.open(sys.argv[1])
    im = im.crop(( left, upper, right, lower))
    im.save(sys.argv[2])

Hope this helps :)

like image 91
Andrew Cox Avatar answered Dec 12 '22 10:12

Andrew Cox