OpenCV图像处理---图片ROI区域选择

import cv2
import os, sys

roiFrame = ''


def FrameSelection(event, x, y, flags, param):
    try:
        global point1, point2

        # resize图片大小
        imgResize = roiFrame.copy()
        img2 = roiFrame.copy()
        if event == cv2.EVENT_LBUTTONDOWN:         #左键点击
            point1 = (x,y)
            cv2.circle(img2, point1, 10, (0,255,0), 5)
            cv2.imshow('image', img2)
        elif event == cv2.EVENT_MOUSEMOVE and (flags & cv2.EVENT_FLAG_LBUTTON):     #按住左键拖曳
            cv2.rectangle(img2, point1, (x,y), (255,0,0), 5)
            cv2.imshow('image', img2)
        elif event == cv2.EVENT_LBUTTONUP:         #左键释放
            point2 = (x,y)
            cv2.rectangle(img2, point1, point2, (0,0,255), 5)
            cv2.imshow('image', img2)
            min_x = min(point1[0],point2[0])     
            min_y = min(point1[1],point2[1])
            width = abs(point1[0] - point2[0])
            height = abs(point1[1] - point2[1])

            # 矩形ROI区域框选的信息
            cut_img = imgResize[min_y:min_y+height, min_x:min_x+width]
            # 写入坐标.txt文件
            f = open('./coordinateLeft.txt','w') 
            # x坐标,y坐标,宽度,高度
            f.writelines([str(min_x),'\n',str(min_y),'\n',str(width),'\n',str(height)])
            f.close()

            cv2.imwrite('afterROI.jpg', cut_img)
            k = cv2.waitKey(0)
            if k & 0xFF == ord('q'):
                cv2.destroyAllWindows()
                return
    except:
        pass

if __name__ == "__main__":
    roiFrame = cv2.imread("./test.jpg")
    cv2.namedWindow('image', cv2.WINDOW_NORMAL)
    cv2.resizeWindow('image', 1000, 1000)
    cv2.setMouseCallback('image', FrameSelection)
    cv2.imshow('image', roiFrame)
    cv2.waitKey(0)

猜你喜欢

转载自blog.csdn.net/HHH_LLL/article/details/106619372