How do I access my webcam in Python?

OpenCV has support for getting data from a webcam, and it comes with Python wrappers by default, you also need to install numpy for the OpenCV Python extension (called cv2) to work. As of 2019, you can install both of these libraries with pip: pip install numpy pip install opencv-python More information on using OpenCV with Python. An example copied … Read more

What is a unicode string?

Update: Python 3 In Python 3, Unicode strings are the default. The type str is a collection of Unicode code points, and the type bytes is used for representing collections of 8-bit integers (often interpreted as ASCII characters). Here is the code from the question, updated for Python 3: Working with files: Historical answer: Python 2 In Python 2, … Read more

What is the difference between random.randint and randrange?

The docs on randrange say: random.randrange([start], stop[, step]) Return a randomly selected element from range(start, stop, step). This is equivalent to choice(range(start, stop, step)), but doesn’t actually build a range object. And range(start, stop) returns [start, start+step, …, stop-1], not [start, start+step, …, stop]. As for why… zero-based counting rules and range(n) should return n elements, I suppose. Most useful for getting a random index, I suppose. While randint is documented … Read more

How do I merge lists in python? [duplicate]

+ operator can be used to merge two lists. Lists can be merged like this in python. Building on the same idea, if you want to join multiple lists or a list of lists to a single list, you can still use “+” but inside a reduce method like this,

threshold in 2D numpy array

One solution: The first part array < 25 gives you an array of the same shape that is 1 (True) where values are less than 25 and 0 (False) otherwise. Element-wise multiplication with the original array retains the values that are smaller than 25 and sets the rest to 0. This does not change the … Read more

Superscript in Python plots

You just need to have the full expression inside the $. Basically, you need “meters $10^1$”. You don’t need usetex=True to do this (or most any mathematical formula). You may also want to use a raw string (e.g. r”\t”, vs “\t”) to avoid problems with things like \n, \a, \b, \t, \f, etc. For example: … Read more

How do I add two sets?

All you have to do to combine them is Sets are unordered sequences of unique values. a | b or a.union(b) is the union of the two sets (a new set with all values found in either set). This is a class of operation called a “set operation”, which Python sets provide convenient tools for.