Recent Entries 10
- pattern minor 112d agoMotion detection program for snapping of imagesI'm doing a motion detection program where it snaps an image when it detects movement and snaps an image of the person's face if in view while this is all recorded and sends it all to Dropbox. It's moving very slowly and lagging like crazy, showing 1 frame in like a minute. Is there a way to optimize it? I'm using a Raspberry Pi to code all this, and a webcam. ``` import sys sys.path.append('/usr/local/lib/python3.4/site-packages') import numpy as np import cv2 import imutils from imutils import contours import datetime import time import dropbox #Function fo Drawing rect and changing text to REC def draw_rect_movement(c): #Draw Rectangle around found contour object (x, y, w, h) = cv2.boundingRect(c) cv2.rectangle(frame, (x,y), (x+w,y+h), (0,255,0), 2) text = "REC" return c def saveNupload(roi_color): #writing image of face as png in the file timestring = time.strftime("%Y_%m_%d_%H_%M_%S") face_timestr = 'face_' + timestring + '.png' cv2.imwrite(face_timestr, roi_color) #Opening for [r]eading as [b]inary FaceFile = open(face_timestr, mode = "rb") #Reads the number of bytes of the video data = FaceFile.read() #Setting the save location with file name SavetoLocation = '/FYP_Face_Save/'+ face_timestr SaveToLocation = str(SavetoLocation) dbx.files_upload(data, SaveToLocation) #Close for reading and binary FaceFile.close() dbx = dropbox.Dropbox('Access Token') dbx.users_get_current_account() #cap = cv2.VideoCapture("/home/pi/Desktop/Proj/VideoTestSample.mp4") cap = cv2.VideoCapture(1) #Creating froeground and removing Background fgbg = cv2.createBackgroundSubtractorMOG2(detectShadows=False) #Set format fourcc = cv2.VideoWriter_fourcc(*'XVID') #Get Datetime timestr = time.strftime("%Y_%m_%d_%H_%M_%S") #Creating name of folder timestr = timestr + '.avi' #Setting Name, Format, FPS, FrameSize out = cv2.VideoWriter(timestr,fourcc, 10.0, (640, 480)) #setting casacade for use face_c
- pattern minor 112d agoStreaming H264 video from PiCamera to a JavaFX ImageViewI'm currently working on a robotics application where a video feed is being displayed from a Raspberry Pi 3. I've been working on a way to stream the video directly into JavaFX (the rest of the UI is created in this), however, my knowledge of video streaming is very limited. The goal for the video system is to maintain decent video quality and FPS while reducing latency as much as possible (looking for sub 100 ms). H264 video was chosen as the format for it's speed, but I hear that sending raw video could be faster as there is no compression (could not get raw video to work well at all). Running my code I am capable of streaming a Pi camera at about 120-130ms of latency and ~48 frames per second. I would like to continue to reduce the latency of this application, and would like to make sure that I'm making decisions for the correct reasons. The largest issue I have so far is start-up time; it takes about 15-20 seconds for the video to initially launch and catch up to the latest frame. The following code is an MCVE of the video system. If anyone is interested in reproducing this, you can get it running on a Raspberry Pi (mine is a Raspberry Pi 3) with `python-picamera` installed. You'll also need a Java Client with JavaCV installed. My version info is `org.bytedeco:javacv-platform:1.3.2`. Python side: We decided to use a Python library to control the video stream because it provides a nice wrapper around the `picamera` command-line tool. The output from the video is being sent over a TCP connection and will be received by a Java client. (The way we remotely launch this application has been left out of the review because I just wanted this post to focus on the video aspects) `import picamera import socket import signal import sys with picamera.PiCamera() as camera: camera.resolution = (1296, 720) camera.framerate = 48 soc = socket.socket() soc.connect((sys.argv[1], int(sys.argv[2]))) file = soc.makefile('wb') try: camera.start
- pattern minor 112d agoWebcam frame splitterI wrote a camera streaming app for pizero. Since the pizero is too weak to do any video encoding I am using it to just capture usb webcam frames (mjpeg format) and forward them over udp to a powerful pc that does the video encoding. When the light conditions are low there is a lot of noise introduced to the frames and they grow in size, overflowing the udp write size limit. To tackle the issue I wrote a func that splits the frame in parts and forwards the pieces to the encoder. What I am looking for in this review is the following: Performance - App runs on pizero where resources are limited. I am using buffered channels and I am not sure if I implemented them correctly. Best practices Hidden pitfalls - If any, point out if I shot myself in the foot. Code contains the whole camera implementation plus the server side. Please review both. My programming level is beginner. This is my first project. Camera: ``` package main import ( "bytes" "fmt" "log" "math" "net" "os/exec" "sync" "time" "labix.org/v2/mgo/bson" ) const ( FFMPEG_ENCODER = "192.168.178.200:8000" CAM_ADDR = ":5000" PACKET = 60000 ) type msg struct { Fragment bool FragmentID int LastFragment bool Data []byte } type reporting struct { Fps int Size int Fragments float64 Encoding time.Duration Writing time.Duration } func main() { conn, err := udpDial() if err != nil { log.Fatal(err) } var stderr bytes.Buffer //bash script with commands for interfacing with the camera. //script outputs to stdout. cmd := exec.Command("./v4l2") pipe, _ := cmd.StdoutPipe() defer pipe.Close() cmd.Stderr = &stderr if err := cmd.Start(); err != nil { fmt.Println(fmt.Sprint(err) + ": " + stderr.String()) } //pizero - has issues serializing. buffer := make(chan [][]byte, 500) var wg sync.WaitGroup var sta
- pattern minor 112d agoPython siren controlBelow is some code I've put together to contol a siren for a fire service. It works by webscraping a paging feed and looks for set triggers. Is there a better way of doing my code or is this "pythonic" enough or can it be improved? Im python self taught. ``` """PYTHON SCRIPT TO CONTROL SIREN This script will webscape a paging feed and in turn activate a siren on set incidents siren should only sound for 30secconds between 0800 -2000 hrs this has been made so the siren only goes off for some incidents not all by s.rees (c) 2016 """ from scraper import Scraper import sys import requests from clint.textui import puts, colored import RPi.GPIO as GPIO from time import sleep import time time = datetime.datetime.now() print "Starting" print "Monitoring" #Set GPIO siren is attached too GPIO.setmode(GPIO.BOARD) GPIO.setup(7, GPIO.OUT) def siren (): GPIO.output(7, GPIO.HIGH) sleep(30) GPIO.output(7, GPIO.LOW) if __name__ == "__main__": # Load webscraper module scraper = Scraper(5, recent_messages=True) @scraper.register_handler def handler(msg): # get msg from scraper and make it readable puts(colored.yellow(msg.channel), newline=False) puts(" [", newline=False) puts(colored.green(msg.datetime), newline=False) puts("] ", newline=False) if msg.response: puts(colored.red(msg.text)) else: puts(msg.text) # set agency if 'MFS' in msg.channel: #set unit if 'Station' in msg.channel: print "Brigade Found" #set response type if 'RESPOND RUBBISH OR WASTE' in msg.text: print "Trigger found" if (time > datetime.time(8) and time datetime.time(8) and time < datetime.time(20)): print "Activate Siren" siren () print 'done' return else: print "out of time restrictions" return
- pattern moderate 112d agoReading a DHT11 to a fileDisclaimer: not a Pythonista, first actual Python programme written right here. I'm reading a DHT11 sensor from GPIO pin 4 on my Raspberry Pi (thanks Thomas Ward for sending the RPi to me), and I want to log it to a file which will later be parsed into a web-page. So I wrote the following Python script which is called by a Cron job every minute, and it reads the sensor 5 times then logs the average, min and max to a file for humidity and temperature. Without further ado, here's my crap: ``` #!/usr/bin/python import sys import Adafruit_DHT import time def getLine(array): return str(sum(array) / float(len(array))) + "," + str(min(array)) + "," + str(max(array)) sensor = Adafruit_DHT.DHT11 gpio = 4 h = [] t = [] count = 5 date = time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime()) for num in range(count): th, tt = Adafruit_DHT.read_retry(sensor, gpio) h.append(th) t.append(tt) with open("MainLog.txt", "a") as file: file.write(date + ": ") # Write Humidity data file.write(getLine(h)) file.write(" | ") file.write(getLine(t)) # Write line break file.write("\n") ``` I have no idea how "good" or "bad" it is, if it were C# I would know but it's not. All suggestions welcome. When I get my new hardware (looks like two-three days from now) I'm going to be adding a BMP180 sensor (barometric pressure/altitude). The `Adafruit_DHT` library is on GitHub: https://github.com/adafruit/Adafruit_Python_DHT I'm going to be replacing this with a DHT22, but that's one LoC change: ``` sensor = Adafruit_DHT.DHT11 ``` To: ``` sensor = Adafruit_DHT.DHT22 ```
- pattern minor 112d agoReading analog moisture signal from Arduino over USB to RPi3 and publishing via paho MQTTThis program is meant to read a moisture sensor attached to an Arduino UNO board via USB to a Raspberry Pi3 which broadcasts it over MQTT. I am looking for any constructive criticism. ``` import serial import time import RPi.GPIO as GPIO import paho.mqtt.client as mqtt def main(): try: while 1: sendMQTT(read_sensor("clean"),"Planty/moisture_readings") alerts() except KeyboardInterrupt: print "\n\nExiting via Keyboard Interrupt" def debugger(): # This is just to test each reading moisture_clean = read_sensor("clean") output = "Soil Moisture is " + str(moisture_clean) + "%" moisture_raw_adjusted = read_sensor("raw_adjusted") output += "\nRaw_adjusted is " + str(moisture_raw_adjusted) moisture_raw = read_sensor("raw") output += "\nRaw is " + str(moisture_raw) sendMQTT(output, "Planty/debug") def alerts(): # Generates alerts that are humanly readable for certain moisture thresholds moisture = read_sensor("clean") alert_low = 10 alert_high = 90 alert_threshold = 30 if moisture alert_low: output = "***Moisture is between 10%` and 30%, watering***" relay(14) time.sleep(60*1) if moisture >= alert_high: output = "***Moisture is above 90%***" sendMQTT(output, "Planty/alerts") def read_sensor(choice): # Read analog moisture data from moisture probe via Arduino UNO plugged into # the RPi via USB min = 330 max = 970 ser = serial.Serial('/dev/ttyACM0', 9600) #Line below handles the problem of the Arduino returning more than 1 reading raw_data = int(str.split(ser.readline())[0]) if choice == "raw": moisture = raw_data #Stop readings going over or under 0 or 100% if raw_data max: raw_data = max if choice == "raw_adjusted": moisture = raw_data if choice == "clean": #Get moisture as % reading moisture = int(round(100-(100/float(max-min))*(raw_data
- pattern minor 112d agoPygame SlideshowI have written a basic slideshow program that uses pygame to manage the display screen. It cycles through all pictures files in the directory and sub-directories. There is a user configuration section for the start directory, sub-directories to ignore, image file type, display time, full screen or window display and adj_height. I like the window display to see the title of the picture. On the Raspberry Pi, I changed the title font to size 18, color blue in Menu, Preferences, Appearance Setting. The window display has a height adjustment to compensate for menu and title bar as I could not find how to get maximum window height before making the window. I would like a code review. My start program seems a little awkward. Any other points would be great. ``` #!/usr/bin/env python """ Picture Slideshow that uses pygame. This slideshow program will loop continuous on the directory, from user configuration or command line argument, and sub- directories skipping thoses in the ignore list. It will display pictures in regular size or reduce them if bigger than the screen size. It will only display files with extension in the configuration file list of my_image_file. To exit the program, click the mouse in the window or exit button. The keyboard ESC or q key will also exit the program, on ssh terminal use CTRL-C. Only tested on the Raspberry Pi 3. """ import os import sys import pygame from pygame.locals import FULLSCREEN from colorama import Fore, Style # User Configurations display_time = 2.5 # Time in seconds full_screen = False # False equal window # full_screen = True Dir = '/home/pi/Pictures' # Directories to ignore ignore = 'Junk', 'Trash', 'Paintings' my_image_files = '.bmp', '.jpg', '.JPG', '.png', '.gif', '.tif' Title = 'Picture Slideshow' # Adjust height of window for menu and title bar. adj_height = 76 # Setup Variables os.environ['DISPLAY'] = ':0.0' # grey = 211, 211, 211 grey = 128, 128, 128 black = 0, 0, 0 magenta = 100, 0, 100
- pattern minor 112d agoBash script for setting up a LAN to WLAN routerI wrote a bash script for the Raspberry Pi 3 (Raspbian) which has the main task of setting up a LAN to WLAN router. In addition it makes some things nicer for the intended users who have Windows background only. It will be used on a Pi 3 with built-in WLAN and the official 7" display only. Preconditions to run the script are (typically done on Windows, so my script can't help here): - download latest Raspbian - flash to SD card - copy 3 files to the /boot partition: the script, a file `asplash` and `splash.png` - insert in Pi and run Raspbian - configure an Internet connection - run the script (`/boot/script.sh`) The script shall - update the sources (`apt-get update`) - upgrade the installation (`apt-get upgrade`) - install required packages to make all of the following work - set keyboard to German - set timezone to Berlin - forward IPv4 from LAN (eth0) to WLAN (wlan0) - configure LAN (eth0) to 192.168.63.1 so it can act as a gateway on the 192.168.63.0/24 network - replace the Raspberry boot output by a nice logo so that the user knows it'll be the right thing on startup - set the Desktop background by the same nice logo The order of those things is not really important, but it seems that the Ethernet configuration should only be done when no Internet access is needed any more, since the script might disable Internet access if the original connection was made over LAN. Yeah, that's it. My tests seem ok, but since this is my first larger bash script, I'd like to get some feedback on how to improve things in the future. ``` #!/bin/sh echo "Setting up this device as a LAN to WLAN gateway..." [ -f /boot/splash.png ] && echo "Splash screen found" || { echo "Please copy splash.png"; exit 1; } [ -f /boot/asplash ] && echo "Splash screen script found" || { echo "Please copy a file called asplash"; exit 1; } ping 8.8.8.8 -c 1 -q -w 1 > /dev/null && echo "Internet connection detected" || { echo "Make sure you have a valid Internet connection." ; exit 1;
- pattern minor 112d agoRaspberry Pi headless server using bash and USB automountingRevised from: Bash scripts and udev rules to handle USB auto mounting / unmounting Tested: Uses USB insert/remove to control a headless Raspberry Pi 3 with Raspian Jessie Lite Changes: - Implement more functions - Improve comments - Modify if-fi exit handling - Add optional flag for auto processing on insert/remove - Optional function for USB insert - copy file (future: read config/start streaming process) - Optional auto shutdown for USB removal (future: close process started by insert) Goals: - Improve bash coding and learn by implementing suggestions - Improve my understanding of if-fi blocks and using inline commands (I'm not confident at all when it comes to streamlining code) Current Code: Uses udev rules to automount USB and create folder for device. Optionally can use an init constant to cause the automount/dismount process to auto start a process (in this case copy a config file) and shutdown pi on removal. Work Flow: ``` uDev rules usb-initloader.sh Insert -> usb-automount.sh Remove -> usb-unloader.sh ``` udev rules ``` # /etc/udev/rules.d/85-usb-loader.rules # ADD rule: # if USB inserted, # and flash drive loaded as sd# # pass on dev name and device formatting type # run short script to fork another processing script # run script to initiate another script (first script must finish quickly) # to mkdir and mount, process file # # reload rules on PI by: # sudo udevadm control --reload-rules # ACTION=="add", KERNEL=="sd*[0-9]", SUBSYSTEMS=="usb", RUN+="/home/pi/scripts/usb-initloader.sh ADD %k $env{ID_FS_TYPE}" ACTION=="remove", KERNEL=="sd*[0-9]", SUBSYSTEMS=="usb", RUN+="/home/pi/scripts/usb-initloader.sh %k" ``` usb-initloader.sh ``` #!/bin/bash # # /home/pi/scripts/usb-initloader.sh # # this script uses udev rules # is initiated when usb device is inserted or removed # # ** DEVICE INSERTED - new USB device inserted ** # ---------
- pattern minor 112d agoPillow-based basic GUI library for an LCDI am working with an LCD screen and an RPi. The library I use sends 1-bit images to the screen, so I wrote this library based on Pillow to help developing the on-screen GUI. I am playing with the thought to release this on the appropriate forums. I would really appreciate some feedback, and this is one of the only places where I can get any. Apart from that, I am also curious if the approach I took is good, and what should I do before actually releasing the code. About the code: I made it running without the two device-specific modules. Normally it would work as in the `main()` function. I tried to be as documented and readable as I could, and I also included some error handling. ``` #!/usr/bin/env python # -*- coding: utf-8 -*- # # untitled.py # # Copyright 2016 Gergely Nagy # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, # MA 02110-1301, USA. # # __author__ = "Gergely Nagy" __license__ = "GPL" __version__ = "0.1b" __status__ = "development" import time from PIL import Image, ImageDraw, ImageFont, ImageChops debugging = True if not debugging or __name__!='__main__': # These device-specific modules are only neccessary if using a real Nokia 5110 # LCD screen, for debug usage (LcdCanvas.target is None) they can be left out import PCD8544 as LCD import Adafruit_GPIO.SPI as SPI # Nokia LCD s