OpenCV의 MouseCallback으로 마우스 클릭으로 연속해서 Drawing 해서 이미지를 생성하는 예제

입니다.  종료하고자 할 경우 Eac Key를 입력하면 되며, 그 전까지는 OpenCV는 계속 유지됩니다.

 

[함수설명]

     cv2.setMouseCallback(windowname, callback, param=None)

             Paramaters : windowname : windowName

                              callback : callback 함수에는 (eventm x, y, flag, param) 이 전달됩니다.

                              param : callback함수에 전달돠는 data

 

OpenCV의 MouseCallback 으로 이미지 그리기 예제

 

# OpenCV MouseCallback
import cv2
import numpy as np

drawing = False # True is Mouse Click
ix, iy = -1, -1

# Mouse Callback
def draw_circle(event, x, y, flags, param):
     global ix, iy, drawing, mode

     if event == cv2.EVENT_LBUTTONDOWN:
          drawing = True
          ix, iy = x, y

     if event == cv2.EVENT_MOUSEMOVE:
         if drawing == True:
            cv2.circle(img, (x, y), 5, (0, 255, 0), -1)

         elif event == cv2.EVENT_LBUTTONUP:
              drawing = False
              cv2.circle(img, (x, y), 5, (0, 255, 0), -1)

# black Area Create
img = np.zeros((512, 512, 3), np.uint8)
cv2.namedWindow('image')
cv2.setMouseCallback('image', draw_circle)

while(1):
     cv2.imshow('image', img)
     k = cv2.waitKey(1) & 0xFF

     if k == 27: # Esc Key
     break

cv2.destroyAllWindows()

# image Save
image_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
cv2.imwrite('C:/Users/sunan/PycharmProjects/NewPJ3.7/OenCV/IMAGE/test_gray.jpg', image_gray)

 

실행 결과

 

OpenCV 실행후 마우스로 직접 그린 이미지

 

 

OpenCV 의 Haar-cascade 로 얼굴 인식 예제

 

# Haar-cascade Detection in OpenCV
import cv2

scaler = 0.35
cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')

img = cv2.imread('adorable-baby-beautiful.jpg')
img = cv2.resize(img, (int(img.shape[1] * scaler), int(img.shape[0] * scaler)))

imageGray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

faceRect = cascade.detectMultiScale(imageGray, 1.3, 5)

for (x, y, w, h) in faceRect:
    cv2.rectangle(img, (x, y),(x+w, y+h), (255, 0, 0), 2)
    roi_gray = imageGray[y:y+h, x:x+w]
    roi_color = img[y:y+h, x:x+w]

cv2.imshow('Baby', img)
cv2.waitKey(0)
cv2.destroyAllWindows()

 

실행 결과

 

[이미지 출처 : https://www.pexels.com/search/videos/face] OpenCV 의 Haar-cascade 로 얼굴 인식 예제 

 

 

Object  : cv2.VideoWriter(outputFile, fourcc, frame, size)

paramater : outputFile : 저장될 화일명

                fourcc : Codex 정보 (각 OS 마다 지원되는 codex이 다를 수 있습니다)

                 frame : 초당 자정될 프레임수

                 size : 저장될 이미지 크기 (ex : 640, 480)

 

OpenCV로 동영상 저장하기 예제

import cv2

cap = cv2.VideoCapture(0) # Video Count Number
fourcc = cv2.VideoWriter_fourcc(*'DIVX') # Codec info

# cv2.VideoWriter(outputFile, fourcc, frame, size)
writer = cv2.VideoWriter('Output.avi', fourcc, 30.0, (640, 480))

while(True):

    ret, img_frame = cap.read()
    if ret:
        img_gray = cv2.cvtColor(img_frame, cv2.COLOR_BGR2GRAY)
        cv2.imshow('Image FRAME ', img_frame)
        if cv2.waitKey(1) & 0xFF == 27: # ESC Key
            break
    else:
        break

cap.release() # Video resource clear
writer.release() # Write File Clear
cv2.destroyAllWindows() # Windows resource clear

 

실행 결과

 

실행된 동영상의 일부 캡쳐 이미지

 

해당 폴더에 Output.avi 화일로 저장

 

 

OpenCV로 이미지 읽기와 저장하기 예제

 

import cv2

# Image Read
img_color = cv2.imread('openCV.png', cv2.IMREAD_COLOR)

cv2.namedWindow('Show Image')
cv2.imshow('Show Image', img_color) # Original Image Show

cv2.waitKey(0) # windows Key Wait Time(sec)

img_gray = cv2.cvtColor(img_color, cv2.COLOR_BGR2GRAY) # Color image gray Color image Change

cv2.imshow('Show GrayScale Image', img_gray) # Gray Image Show
cv2.waitKey(0) # windows Key Wait Time(sec)

cv2.imwrite('save_gray_image.png', img_gray)  #  Fray Image save

cv2.destroyAllWindows() # windows resources clear

 

실행결과

 

원래이미지 출력

 

그레이로 변경된 이미지 출력

 

+ Recent posts