[DIP] OpenCV : Region of Interest (ROI) : Callback으로 구현.

2022. 10. 3. 21:13·Programming/DIP
728x90
728x90

cv2.selectROI가 아닌 이벤트 핸들러(MouseCallback)를 이용한 구현임.

  • x button (or close button)을 지원하기 위한 구현을 추가.
  • x 키를 누를 경우, roi를 보여주는 창만 닫히도록 처리함.
  • esc 키를 누를 경우, 프로그램 종료.
import cv2
import numpy as np

is_dragging = False

x0,y0 = -1,-1
w0,h0 = -1,-1
red = (0,0,255)
exit_roi = False

import os
d_path = os.path.dirname(__file__)
f_path = os.path.join(d_path,"lena.png")

def onMouse(event, x, y, flags, param):

    global is_dragging
    global x0,y0,w0,h0
    global exit_roi
    
    if event == cv2.EVENT_LBUTTONDOWN:
        is_dragging = True
        x0 = x
        y0 = y
        print(x0,y0)

    elif event == cv2.EVENT_MOUSEMOVE:
        if is_dragging:
            tmp = img.copy()
            cv2.rectangle(tmp, (x0,y0), (x,y), red, 2)
            cv2.imshow('roied_img', tmp)

    elif event == cv2.EVENT_LBUTTONUP:
        if is_dragging:
            is_dragging = False
            w = x-x0
            h = y-y0

            if w>0 and h > 0:
                tmp = img.copy()

                cv2.rectangle(tmp, (x0,y0), (x,y), red, 3)
                cv2.imshow('roied_img', tmp)
                exit_roi = True
                roi = img[y0:y0+h, x0:x0+w]
                #roi = img[x0:x0+w, y0:y0+h]
                cv2.imshow('roi', roi)
                cv2.moveWindow('roi',0,0)
                cv2.imwrite(f'{d_path}/roi.png',roi)
                print('roi is cropped and saved!')
            else:
                cv2.imshow('roied_img', img)
                print('unvalid roi!. select roi carefully')
    return
img = cv2.imread(f_path)
cv2.imshow('roied_img', img)
cv2.setMouseCallback('roied_img',onMouse)

while cv2.getWindowProperty('roied_img', cv2.WND_PROP_VISIBLE) >= 1:
    key_code = cv2.waitKey(50) & 0xff # millisecond
    if key_code != 255:
        print(key_code, ord('x'),exit_roi)

    if key_code == 27:
        # print('ESC')
        break;
    elif exit_roi and key_code == 120:
        print('closed button')
        exit_roi = False
        cv2.destroyWindow('roi')
    elif cv2.getWindowProperty('roied_img', cv2.WND_PROP_VISIBLE) < 1:
        # print('closed button')
        break;
    elif exit_roi and cv2.getWindowProperty('roi', cv2.WND_PROP_VISIBLE) < 1:
        # print('closed button')
        exit_roi = False
        cv2.destroyWindow('roi')

cv2.destroyAllWindows()

 

ROI만 선택하는 간단한 버전이 필요하다면 다음을 참조할 것.

2022.10.03 - [Programming/DIP] - [DIP] opencv : Region of Interest (ROI) : cv2.selectROI

 

[DIP] opencv : Region of Interest (ROI) : cv2.selectROI

cv2에서 사각형의 ROI를 선택하는 가장 쉬운 방법. ret_val = cv2.selectROI([window_name], img [, showCrossHair=True, fromCenter=False] window_name : ROI 선택을 수행할 window이름. str img : 보여질 이미..

dsaint31.tistory.com


같이 보면 좋은 자료들.

https://dsaint31.me/mkdocs_site/DIP/cv2/ch00/dip_0_03/#mouse-as-a-paint-brush

 

BME228

Mouse as a Paint-Brush 이 문서의 코드는 cv2.imshow가 가능한 local 서버에서 동작하는 jupyter note 등을 대상으로 구현됨. Colab 이나 원격지 서버에서 동작중인 jupyter note등에서는 동작하지 않음. Goal OpenCV

dsaint31.me

https://ds31x.tistory.com/37

 

[Python] Callback function

Callback Functioncallback function란 다음 두가지에 해당하는 function을 의미한다.다른 function의 argument로 전달되어 특정 event가 발생시 호출이 이루어지는 function을 가르킨다 (사용자가 명시적으로 호출

ds31x.tistory.com


 

'Programming > DIP' 카테고리의 다른 글

[DIP] Deconvolution: Richardson-Lucy deconvolution algorithm  (0) 2022.10.11
[NumPy] Fancy Indexing & Combined Indexing  (1) 2022.10.03
[DIP] opencv : Region of Interest (ROI) : cv2.selectROI  (1) 2022.10.03
[NumPy] Broadcasting  (0) 2022.09.27
[DIP] Signal to Noise : Amplitude, Power, and Differential SNR  (0) 2022.09.26
'Programming/DIP' 카테고리의 다른 글
  • [DIP] Deconvolution: Richardson-Lucy deconvolution algorithm
  • [NumPy] Fancy Indexing & Combined Indexing
  • [DIP] opencv : Region of Interest (ROI) : cv2.selectROI
  • [NumPy] Broadcasting
dsaint31x
dsaint31x
    반응형
    250x250
  • dsaint31x
    Dsaint31's blog
    dsaint31x
  • 전체
    오늘
    어제
    • 분류 전체보기 (748)
      • Private Life (13)
      • Programming (56)
        • DIP (112)
        • ML (26)
      • Computer (119)
        • CE (53)
        • ETC (33)
        • CUDA (3)
        • Blog, Markdown, Latex (4)
        • Linux (9)
      • ... (351)
        • Signals and Systems (103)
        • Math (172)
        • Linear Algebra (33)
        • Physics (42)
        • 인성세미나 (1)
      • 정리필요. (54)
        • 의료기기의 이해 (6)
        • PET, MRI and so on. (1)
        • PET Study 2009 (1)
        • 방사선 장해방호 (4)
        • 방사선 생물학 (3)
        • 방사선 계측 (9)
        • 기타 방사능관련 (3)
        • 고시 (9)
        • 정리 (18)
      • RI (0)
      • 원자력,방사능 관련법 (2)
  • 블로그 메뉴

    • Math
    • Programming
    • SS
    • DIP
  • 링크

    • Convex Optimization For All
  • 공지사항

    • Test
    • PET Study 2009
    • 기타 방사능관련.
  • 인기 글

  • 태그

    Python
    linear algebra
    fourier transform
    DIP
    Probability
    math
    인허가제도
    Vector
    SIGNAL
    Optimization
    cv2
    function
    opencv
    Convolution
    Programming
    numpy
    Term
    signal_and_system
    SS
    signals_and_systems
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
dsaint31x
[DIP] OpenCV : Region of Interest (ROI) : Callback으로 구현.
상단으로

티스토리툴바