以交互方式在图像上绘制矩形

时间:2013-12-03 11:27:59

标签: python opencv pygame

是否可以以交互方式在图像上绘制矩形并将坐标存储在python中? 我在c ++中使用OpenCV完成了这个,但在切换到python之后我找不到实现这个目的的方法。

我使用了pygame,以下脚本允许我以交互方式裁剪图像。但不是裁剪我只想要矩形坐标。是否可以使用opencv / pygame或任何类似的库在python中执行此操作?

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, 0, 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])

1 个答案:

答案 0 :(得分:0)

图片的矩形坐标为:

corner_pts = [(left,upper), (left,lower), (right,upper), (right,lower)]

但是,如果您使用的是 pygame,我建议您使用 pygame.Rect 对象和虚拟属性 topleft, bottomleft´, topright, bottomright`:

def mainLoop(screen, px):
    pts = []
    runProgram = True
    while runProgram:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                runProgram = False
            elif event.type == pygame.MOUSEBUTTONUP:
                pts.append(event.pos)
                runProgram = len(pts) < 2
        displayImage(screen, px, topleft)

    x_pts, y_pts = list(zip(*pts)) 
    left, right, top, bottom, = min(x_pts), max(x_pts), min(y_pts), max(y_pts)
    return pygame.Rect(left, top, right-left, bottom-top)
rect = mainLoop(screen, px)
corner_pts = [rect.topleft, rect.bottomleft, rect.topright, rect.bottomright]