
Below is simple code that one can practice with to build a camera capture app. The app allows you to capture an image or video and store it. With this simple code concept and practice, it is now easy to understand how and why we have a lot of social network apps that are using the capture concept to build anything for the users.
A camera capture project in python
STEP 1:
First, you import all the required dependencies. Then using Python and JavaScript, you define the functions.
from IPython.display import display, Javascript
from google.colab.output import eval_js
from base64 import b64decode
def take_photo(filename='photo.jpg', quality = 0.8):
js = Javascript('''
async function takePhoto(quality) {
const div = document.createElement('div');
const capture = document.createElement('button');
capture.textContent = 'Capture';
div.appendChild(capture);
const video = document.createElement('video');
video.style.display = 'block';
const stream = await navigator.mediaDevices.getUserMedia({video: true});
document.body.appendChild(div);
div.appendChild(video);
video.srcObject = stream;
await video.play();
// Resize the output to fit the video element.
google.colab.output.setIframeHeight(document.documentElement.scrollHeight, true);
// Wait for the Capture to be clicked.
await new Promise((resolve) => capture.onclick = resolve);
const canvas = document.createElement('canvas');
canvas.width = video.videoWidth;
canvas.height = video.videoHeight;
canvas.getContext('2d').drawImage(video, 0, 0);
stream.getVideoTracks()[0].stop();
div.remove();
return canvas.toDataURL('image/jpg', quality);
}''')
display(js)
data = eval_js('takePhoto({})'.format(quality))
binary = b64decode(data.split(',')[1])
with open(filename, 'wb') as f:
f.write(binary)
return filename
STEP 2:
Next you, write function that will detect the camera present. If not camera is present, an error message should be displayed.
from IPython.display import Image
try:
filename = take_photo()
print('Saved to {}'.format(filename))
#Show the image which was just taken with the camera present.
display(Image(filename))
except Exception as err:
# Errors will be thrown if the user does not have a camera or webcam on their device
# grant the page permission to access the avialable camera or webcam
print(str(err))
STEP 3:
If your device has a camera, it will open and then capture an image or video and store it in the form you defined previously on your code.
Saved to photo.jpg

That’s it!
This code can be modified to do a lot of things. For example, snapchat, Zao, instagram, tikto, etc.. to name just a few… All these applications uses your camera to provide their product/service to the users.
Now that you have a simple code, your imaginations are endless. Always remember to use it wisely and safely for social good. You can find the code on github using this link.
If you have any question or comment, do not hesitate to ask us.