Showing posts with label openCV. Show all posts
Showing posts with label openCV. Show all posts

Saturday, December 26, 2015

Python, OpenCV: Video Capture and Display

OpenCV: Video Capture

import time
import cv2

video_capture = cv2.VideoCapture(0)
while True:
    t0=time.time()
    ret, frame = video_capture.read()
    t1=time.time()
    print "passed ", t1-t0, "s"

    cv2.imshow('Video', frame)
    #on pressing "q" exit
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
        
video_capture.release()
cv2.destroyAllWindows()  

Frames Per Second Counter

#test how many frames per second for a webcam
import time
import cv2

video_capture = cv2.VideoCapture(1)
t0 = time.time()
i=0
while True:
    ret, frame = video_capture.read()
    print frame.shape
    t = time.time()
    if t-t0 > 1:
        t0=t
        print "frames ",i
        i=0
        
    i+=1    
                    
    cv2.imshow('Video', frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
        
video_capture.release()
cv2.destroyAllWindows()   

Monday, April 20, 2015

OpenCV: Passing Parameters to Trackbar Callback Function

OpenCV Trackbars are created through the system call like below, with a callback function which is called when there is any change on the bar.

createTrackbar("Dummy Trackbar Name", "Dummy Window Name", &pos, max_pos, onTrackbarChange, &u);

Here pos is the pass-by-ref variable that records the current position of trackbar, max_pos denotes its maximum possible value of this variable that the bar can handle. onTrackbarChange is the callback function u is the user data that is passed to the callback function.

onTrackbarChange is prototyped as

void onTrackbarChange(int, void*);

Since there is only limited parameters, the data has to be packaged into an object or a structure like this,

typedef struct {
 Mat* grad;
 Mat* dst;
 Mat* detected_edges;
 int* pos;
 int* ratio;
 int* kernel_size;
 char* window_name;
} userdata;

Of cource, the members within userdata structure could be whatever type you might need. Here I grab a snippet of what my demo is using. Thus you can implement the callback function on demand.

void onTrackbarChange(int pos, void* ud) {
 userdata u = *static_cast(ud);

 // Reduce noise with a kernel 3x3
 blur(*u.grad, *u.detected_edges, Size(3, 3));

 // Canny detector
 Canny(*u.detected_edges, *u.detected_edges, *u.pos, *u.pos*(*u.ratio), *u.kernel_size);

 // Using Canny's output as a mask, we display our result
 *u.dst = Scalar::all(0);

 (*u.grad).copyTo(*u.dst, *u.detected_edges);
 imshow(u.window_name, *u.dst);
        waitKey(0);
}