Skip to content

Instantly share code, notes, and snippets.

@NicolaiSoeborg
Created April 22, 2022 21:59
Show Gist options
  • Save NicolaiSoeborg/e7562e67bb9976a1370c47e4ebc970ad to your computer and use it in GitHub Desktop.
Save NicolaiSoeborg/e7562e67bb9976a1370c47e4ebc970ad to your computer and use it in GitHub Desktop.
from io import BytesIO
from time import sleep, time
from picamera import PiCamera
from PIL import Image, ImageChops
import numpy as np
def take_image(cam, stream):
cam.capture(stream, resize=(320, 240), format='jpeg')
# "Rewind" the stream to the beginning so we can read its content
stream.seek(0)
return Image.open(stream)
def get_entropy(img):
w, h = img.size
a = np.array(img.convert('RGB')).reshape((w*h,3))
h, e = np.histogramdd(a, bins=(16,)*3, range=((0,256),)*3)
prob = h/np.sum(h) # normalize
prob = prob[prob>0] # remove zeros
return -np.sum(prob*np.log2(prob))
if __name__ == '__main__':
idx = 0
streams = [BytesIO(), BytesIO()]
with PiCamera() as cam:
# cam.resolution = (1024, 768)
# Camera warmup (longer => better)
cam.start_preview()
sleep(2)
imgs = [take_image(cam, streams[i]) for i in range(2)]
# TODO: stream.truncate() ?
while True:
diff = ImageChops.difference(imgs[0], imgs[1])
# arr = np.array(diff)
print(get_entropy(diff))
sleep(1 * 60)
streams[idx].seek(0)
imgs[idx] = take_image(cam, streams[idx])
idx = (idx + 1) % 2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment