-1

I'm new to python. I'm writing a program for converting camera input to binary form. It shows there 4 second lag. I'm designing for gesture recognition. So this 4 second lag is not acceptable. Can anyone help me ?

import numpy as np
import cv2,cv 
from PIL import Image
from scipy.misc import imsave
import numpy
def binarize_image(image, threshold):
    """Binarize an image."""
    image = numpy.array(image)
    image = binarize_array(image, threshold)
    return image
def binarize_array(numpy_array, threshold):
    """Binarize a numpy array."""
    for i in range(len(numpy_array)):
        for j in range(len(numpy_array[0])):
            if numpy_array[i][j] > threshold:
                numpy_array[i][j] = 255
            else:
                numpy_array[i][j] = 0
    return numpy_array
cap = cv2.VideoCapture(0)
while(True):
    ret, frame = cap.read()
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    im_bw=binarize_image(gray, 50)


    cv2.imshow('frame',im_bw)
    if cv2.waitKey(1) & 0xFF == ord('q'):
      break

cap.release()
cv2.destroyAllWindows() 
  • 2
    I'd first start by using a profiler to find hotspots. That should be one of the first tools you reach for for situations like this. – Carcigenicate Feb 04 '17 at 02:09
  • how big is your image? I think your binarize_arry function is very inefficient because it individually processes all values from the numpy array in a regular python nested loop. That is a no-no when dealing with numpy. Research numpy specific operations that operate on the whole array at once – Irmen de Jong Feb 04 '17 at 02:16
  • I'm taking input from my webcam which 1280*720 – Prabin Krishna M Feb 04 '17 at 02:18
  • Your `binarize_array` function should be equivalent to just doing `image[image>threshold]`. – Håken Lid Feb 04 '17 at 02:19

1 Answers1

1

You can rewrite your binarize_array to use numpy only (that's what you should always try to do when working with numpy):

>>> a
array([[ 0.45789954,  0.05463345,  0.95972817],
       [ 0.32624327,  0.34981164,  0.4645523 ],
       [ 0.49630741,  0.44292407,  0.29463364]])
>>> mask = a > 0.5
>>> mask
array([[False, False,  True],
       [False, False, False],
       [False, False, False]], dtype=bool)
>>> a[mask] = 1
>>> a[~mask] = 0
>>> a
array([[ 0.,  0.,  1.],
       [ 0.,  0.,  0.],
       [ 0.,  0.,  0.]])
BlackBear
  • 22,411
  • 10
  • 48
  • 86