基礎ユニット2(イメージメディア) 第10回(2020/12/10)

関連サイトと資料

矩形状の関心領域(ROI;Region Of Interest)を指定するサンプルプログラム

RectRoi.py
import cv2
  
def Mosaic(img, bs):
    img2 = cv2.resize(img, None, fx=1/bs, fy=1/bs)
    img3 = cv2.resize(img2, None, fx=bs, fy=bs, interpolation=cv2.INTER_NEAREST)
    return img3
  
def Mouse(event, x, y, flags, param):
    global imgA, imgB, isDrag, Xstart, Ystart, Xend, Yend
  
    if event == cv2.EVENT_LBUTTONDOWN:
        isDrag = True
        (Xstart, Ystart) = (x, y)
    elif event == cv2.EVENT_MOUSEMOVE and isDrag == True:
        imgB[:,:] = imgA[:,:]
        (Xend, Yend) = (x, y)
        cv2.rectangle(imgB, (Xstart, Ystart), (Xend, Yend), (255, 0, 0), thickness=2)
        cv2.imshow('window', imgB) 
    elif event == cv2.EVENT_LBUTTONUP:
        isDrag = False
        imgA[:,:] = imgB[:,:]
        cv2.imshow('window', imgA)
  
if __name__ == '__main__':
    target = 'UCB.jpg'
    blockSize = 10
  
    imgOrg = cv2.imread(target, cv2.IMREAD_COLOR)
    imgA = imgOrg.copy()
    imgB = imgOrg.copy()
  
    isDrag = False
    (Xstart, Ystart) = (0, 0)
    (Xend, Yend) = (0, 0)
  
    cv2.imshow('window', imgA)
    cv2.setMouseCallback('window', Mouse)
  
    while True:
        key = cv2.waitKey(10)
        if key == ord('q'):
            break
  
    cv2.destroyAllWindows()
    

UCB.jpg

プログラム実行直後

マウスで矩形を指定