Python – How to Capture Video Feed from Webcam Using OpenCV

Have you ever written code to interface with a webcam? Well, if you have then you know that it can be a royal pain in the ass. And God forbid you want it to be a cross-platform solution! The good news is that there is a ready-made solution that can help us out: OpenCV. Yes, you heard me right. Not only is OpenCV and amazing computer vision library, but it also provides a handy, cross-platform way of interfacing with webcams. Let’s take a look at how simple OpenCV makes this. I’ll be using Python for these examples, but the API is similar in other languages.

Shut Up and Show Me the Code!

Okay, okay, we’ll take a look at the code already 🙂

import cv2

# Open a handle to the default webcam
camera = cv2.VideoCapture(0)

# Start the capture loop
while True:
	# Get a frame
	ret_val, frame = camera.read()

	# Show the frame
	cv2.imshow('Webcam Video Feed', frame)

	# Stop the capture by hitting the 'esc' key
	if cv2.waitKey(1) == 27:
		break

# Dispose of all open windows
cv2.destroyAllWindows()

Not too surprisingly, running this simple script will open up a window displaying a live video feed from the default webcam. The window can be closed by hitting the escape key. I think this code is pretty self-explanatory, so I won’t dive into it here, but feel free to hit me up if you have any questions!

Quickly Generating Primes Below n With the Sieve of Eratosthenes

The uses for prime numbers in computer science are nearly endless. They are useful for everything from hashing, cryptology, factorization, and all sorts of applications in-between.

There exists a great number of algorithms that allow us to quickly generate primes, but today we are going to take a look at a popular method known as a prime sieve. There are a number of different implementations of prime sieves, but one of the simplest to implement is known as the Sieve of Eratosthenes. This algorithm is great for quickly generating smaller prime numbers (but it may not be the best choice for generating very large primes).

How it Works

In general, the Sieve of Eratosthenes works by generating a list of numbers from 2 to n. The algorithm will then work through the list, marking all the composite numbers. Here is a more detailed breakdown of the implementation:

  1. Create a list of integers from 2 to n. We start at 2 because it’s the smallest prime
  2. Set p=2
  3. Iterate over the multiples of p by counting to n from 2p in increments of p. These are the numbers that get marked as composites in the list.
  4. Find the first number greater than p in the list that is not marked. If one does not exist, we are done. If one does exist, however, set p to this new value and repeat from step 3.

This method has a complexity of $$ O\left(N \cdot log\left(log\left(N\right)\right)\right) $$.

Implementation in Python

Let’s take a look at how we can implement a Sieve of Eratosthenes in Python:

def get_primes():
  D = {}
  p = 2
  
  while 1:
    if p not in D:
      yield p
      D[p*p] = [q]
    else:
      for q in D[p]:
        D.setdefault[q+p, []).append(q)
      del D[p]
    p += 1

For this implementation, I have modified things a bit to yield an infinite prime generator.

Let’s take a moment to consider an example of how this could be used in a practical scenario. Let’s take, for example, problem 10 from Project Euler, which asks that we find the sum of all the primes below 2 million. Using our gen_primes() method we can easily solve this with the following:

primes = gen_primes()
print(sum(itertools.takewhile(lambda x: x < 2000000, primes)))

Another Practical Example

Before I wrap up this post, let’s consider just one more practical use for our gen_primes() method. Assume that we needed to find out what the nth prime is. For the purpose of example, let’s just say we want to find the 500th prime number. It turns out this can be done easily with the following:

primes = gen_primes()
print(next(itertools.islice(primes, 500, None), None))

Running this will reveal that the 500th prime number is 3,581.

Wrap Up

As I hope you can see, the Sieve of Eratosthenes is a simple way to generate prime numbers that can prove useful in a number of situations. I hope you’ve found this helpful!

How to Route Urllib2 Through Tor (Python)

I’ve recently been experimenting on a new project to scrape data from webpages located on the Tor network. For simplicity’s sake, I decided to write this bit of code in Python and use the handy urllib2 library to handle the HTTP requests.

For those that don’t know, Tor runs a SOCKS5 proxy, which, by default, runs on 127.0.0.1:9050. I thought things would be as simple as telling urllib2 to use a proxy located at IP 127.0.0.1 and port 9050, but I quickly found that this doesn’t work.

Luckily, after a bit of digging, I found a solution. It turns out that urllib2 uses Python’s socket module, which contains the method create_connection(). If we take a look at the code for this method we can see where our problem lies:

def create_connection(address, timeout=_GLOBAL_DEFAULT_TIMEOUT,
                      source_address=None):
    """Connect to *address* and return the socket object.
 
   Convenience function.  Connect to *address* (a 2-tuple ``(host,
   port)``) and return the socket object.  Passing the optional
   *timeout* parameter will set the timeout on the socket instance
   before attempting to connect.  If no *timeout* is supplied, the
   global default timeout setting returned by :func:`getdefaulttimeout`
   is used.  If *source_address* is set it must be a tuple of (host, port)
   for the socket to bind as a source address before making the connection.
   An host of '' or port 0 tells the OS to use the default.
   """
 
    msg = "getaddrinfo returns an empty list"
    host, port = address
    for res in getaddrinfo(host, port, 0, SOCK_STREAM):
        af, socktype, proto, canonname, sa = res
        sock = None
        try:
            sock = socket(af, socktype, proto)
            if timeout is not _GLOBAL_DEFAULT_TIMEOUT:
                sock.settimeout(timeout)
            if source_address:
                sock.bind(source_address)
            sock.connect(sa)
            return sock
 
        except error, msg:
            if sock is not None:
                sock.close()
 
    raise error, msg

In looking at this we can see that, even though we specified that Tor should be used as our proxy, the create_connection() function will still perform the DNS request using the default settings, hence bypassing the Tor network. Luckily, we can create our own create_connection() method and jerry-rig it into the socket class before we load urllib2. In doing this we can force the DNS request to go through Tor, thus allowing us to route our urllib2 traffic through the Tor network. This can be achieved with the following bit of code:

import socket
import socks
 
# urllib2 uses the socket module's create_connection() function.
# The way the DNS request is done won't work for our Tor connection,
# so we need to jerry-rig our own create_connection() for urllib2
def create_connection(addr, timeout=None, src=None):
  sock = socks.socksocket()
  sock.connect(addr)
  return sock
 
# Set our proxy to TOR
socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, '127.0.0.1', 9050)
 
socket.socket = socks.socksocket
socket.create_connection = create_connection # force the socket class to use our new create_connection()
 
import urllib2 # now we can import the urllib :D

With this done any request that we make using the urllib2 class will be performed over the Tor network!