使用opencv python从图像中提取多个ROI

时间:2019-02-23 05:32:41

标签: python opencv

我正在开发一个程序,该程序需要从图像中选择四个点击点,并将140x140小节存储在数据库中的每个点击点周围。我试图将多个图像小节存储在一个列表中,但我做不到。

下面是我用来获得单个点击点的代码。

import cv2
refPt = []
cropping = False

def click_and_crop(event, x, y, flags, param):
    global refPt, cropping

    if event == cv2.EVENT_LBUTTONUP:
        Pt = (x, y)
        refPt=[(x-70,y+70)]
        refPt.append((x+70,y-70))
        cropping = True
        cv2.rectangle(image, refPt[0], refPt[1], (0, 255, 0), 2)

image = cv2.imread('bookscene.jpg')
clone = image.copy()
cv2.namedWindow("image")
cv2.setMouseCallback("image", click_and_crop)

while True:
    cv2.imshow("image", image)
    key = cv2.waitKey(1) & 0xFF

    #reset
    if key == ord("r"):
        image = clone.copy()
    #crop
    elif key == ord("c"):
        break


if len(refPt) == 2:
    roi = clone[refPt[1][1]:refPt[0][1], refPt[0][0]:refPt[1][0]]
    cv2.imshow("ROI", roi)
    cv2.waitKey(0)

cv2.destroyAllWindows()

1 个答案:

答案 0 :(得分:0)

通过执行refPt=[(x-70,y+70)],您会为每次点击重置所有列表。您必须追加鼠标x / y并稍后计算矩形,或者将两个角点存储在一起。

我用您的代码创建了要点,以显示您想要的行为:

import cv2
refPt = []

def show():
    global image, refPt
    # create a copy so the drawn rectangles wont show up in subimages
    img_copy = image.copy()
    # create a subimage in a separate window
    # similar code can be used that checks if 4 points are selected, then saves the subimages and exits script
    i = 0
    for rect in refPt:
        subimage = img_copy[rect[0][1]:rect[1][1],rect[0][0]:rect[1][0]]
        cv2.imshow("image"+str(i), subimage)
        i += 1
    # draw rectangle on full image 
    for rect in refPt:
        cv2.rectangle(img_copy, rect[0], rect[1], (0, 255, 0), 2)
    # show full image
    cv2.imshow("image", img_copy)


def click_and_crop(event, x, y, flags, param):
    global refPt
    if event == cv2.EVENT_LBUTTONUP:
        # create tuples with two opposite cornerpoints and add to list
        point_a = (x-70,y-70)
        point_b = (x+70,y+70)
        refPt.append((point_a,point_b))
        # show images
        show()


# load and display image
image = cv2.imread('opencv-template-matching-python-tutorial.jpg')
cv2.namedWindow("image")
cv2.setMouseCallback("image", click_and_crop)
show()

cv2.waitKey(0)
cv2.destroyAllWindows()