I want to take a series of Images in python with different webcams, stack them and afterwards save them in different folders counted from 1 to 14 for each camera. Stacking is a process by which each pixel of different pictures get summed up and by the end divided by the number of pictures.
Here is my code:
import numpy as np
import time
from time import strftime, localtime, gmtime
import subprocess
import sys
import glob
def install(package):
subprocess.check_call([sys.executable, "-m", "pip", "install", package])
install("opencv-python")
import cv2
###################### Camport Access #####################################################################################
def list_ports():
# Test the ports and returns a tuple with the available ports and the ones that are working.
is_working = True
dev_port = 0
working_ports = []
available_ports = []
while is_working:
camera = cv2.VideoCapture(dev_port)
if not camera.isOpened():
is_working = False
print("Port %s is not working." % dev_port)
else:
is_reading, img = camera.read()
w = camera.get(3)
h = camera.get(4)
if is_reading:
print("Port %s is working and reads images (%s x %s)" % (dev_port, h, w))
working_ports.append(dev_port)
else:
print("Port %s for camera ( %s x %s) is present but does not reads." % (dev_port, h, w))
available_ports.append(dev_port)
dev_port += 1
return available_ports, working_ports
available, camports = list_ports()
print(camports)
picture_count = 5
hours = int(input("amount of hours: "))
minute = localtime().tm_min
for i in range(stunden):
hour = localtime().tm_hour
print("starting hour: ", i)
for j in camports:
cam_port = j
print("currently taking images at camport: ", j + 1)
cam = cv2.VideoCapture(cam_port, cv2.CAP_DSHOW)
# take picture here and safe it
Images = []
timestr = time.strftime("%d.%m.%Y-%H_%M_%S")
for k in range(picture_count):
cam.set(cv2.CAP_PROP_AUTOFOCUS, 0)
time.sleep(0.5)
result, image = cam.read()
if result:
Images.append(image)
img_sum = np.zeros(np.shape(image)) # Sum of images
img_cnt = np.full(image.shape, picture_count)
for img in Images:
img_sum = img_sum + img.astype(float) # Sum images
avg_img = img_sum / img_cnt # Divide sum by count, for computing the average.
avg_img = np.round(avg_img).astype(np.uint8) # Round an cast to uint8
else:
print("failure at: ", j + 1, k + 1)
cv2.imwrite(f"path\\{j + 1}\\pic {i + 1} {timestr}.tiff", avg_img)
print("waiting for the next hour")
while localtime().tm_min is not minute or localtime().tm_hour == hour:
time.sleep(1)
I have a problem while accessing the cameras. Unattached to which camera I'm using the 4th, 6th, 8th, 10th, 12th and 14th camport won't work and give me the message that every picture made has failed. (see "failure at: ").
Do you have an idea how this could be fixed?
Related
The server is sending video by video using the same RTSP URL(rtsp://192.168.0.2:8554/)
I can capture and display video using opencv.
import numpy as np
import cv2 as cv
os.environ["OPENCV_FFMPEG_CAPTURE_OPTIONS"] = "rtsp_transport;udp"
cap = cv.VideoCapture('rtsp://192.168.0.2:8554/')
while cap.isOpened():
ret, frame = cap.read()
# if frame is read correctly ret is True
if not ret:
print("Can't receive frame (stream end?). Exiting ...")
break
cv.imshow('frame', frame)
if cv.waitKey(1) == ord('q'):
break
cap.release()
cv.destroyAllWindows()
This program returns error when going on to the next video.
I tried this, but this didn't work.
import cv2 as cv
import os
import time
os.environ["OPENCV_FFMPEG_CAPTURE_OPTIONS"] = "rtsp_transport;udp"
cap = cv.VideoCapture('rtsp://192.168.0.26:8554/')
if not cap.isOpened():
print("Cannot open camera")
exit()
while True:
try:
time.sleep(2)
# Capture frame-by-frame
ret, frame = cap.read()
# if frame is read correctly ret is True
# Our operations on the frame come here
# Display the resulting frame
cv.imshow('frame',frame)
if cv.waitKey(1) == ord('q'):
break
except:
print("Exception!!")
# When everything done, release the capture
cap.release()
cv.destroyAllWindows()
Can I get some help?
Thanks in advance!
I solved this by using multi-threaded program.
Main file
from datasets import LoadStreams
import threading
import os
import logging
import cv2
import torch
import time
logger = logging.getLogger(__name__)
def select_device(device='', batch_size=None):
# device = 'cpu' or '0' or '0,1,2,3'
cpu_request = device.lower() == 'cpu'
if device and not cpu_request: # if device requested other than 'cpu'
os.environ['CUDA_VISIBLE_DEVICES'] = device # set environment variable
assert torch.cuda.is_available(), f'CUDA unavailable, invalid device {device} requested' # check availablity
cuda = False if cpu_request else torch.cuda.is_available()
if cuda:
c = 1024 ** 2 # bytes to MB
ng = torch.cuda.device_count()
if ng > 1 and batch_size: # check that batch_size is compatible with device_count
assert batch_size % ng == 0, f'batch-size {batch_size} not multiple of GPU count {ng}'
x = [torch.cuda.get_device_properties(i) for i in range(ng)]
s = f'Using torch {torch.__version__} '
for i, d in enumerate((device or '0').split(',')):
if i == 1:
s = ' ' * len(s)
logger.info(f"{s}CUDA:{d} ({x[i].name}, {x[i].total_memory / c}MB)")
else:
logger.info(f'Using torch {torch.__version__} CPU')
logger.info('') # skip a line
return torch.device('cuda:0' if cuda else 'cpu')
def detect(rtsp_url):
dataset = LoadStreams(rtsp_url)
device = select_device('')
count = 0
view_img = True
# img = torch.zeros((1, 3, imgsz, imgsz), device=device) # init img
try:
for frame_idx, (path, img, im0s, vid_cap) in enumerate(dataset): # for every frame
count += 1
im0 = im0s[0].copy()
if view_img:
cv2.imshow(str(path), im0)
# if cv2.waitKey(1) == ord('q'): # q to quit
# raise StopIteration
except:
print("finish execption")
dataset.stop()
return "good"
if __name__ == '__main__':
rtsp_url = "rtsp://192.168.0.26:8554/"
while True:
for thread in threading.enumerate():
print(thread.name)
print(detect(rtsp_url))
dataset class file
import glob
import logging
import math
import os
import random
import shutil
import time
import re
from itertools import repeat
from multiprocessing.pool import ThreadPool
from pathlib import Path
from threading import Thread
import cv2
import numpy as np
import torch
class LoadStreams: # multiple IP or RTSP cameras
def __init__(self, sources='streams.txt', img_size=640):
self.mode = 'stream'
self.img_size = img_size
self.capture = None
self.my_thread = None
self.stopFlag = False
if os.path.isfile(sources):
with open(sources, 'r') as f:
sources = [x.strip() for x in f.read().strip().splitlines() if len(x.strip())]
else:
sources = [sources]
n = len(sources)
self.imgs = [None] * n
self.sources = [clean_str(x) for x in sources] # clean source names for later
s = sources[0]
# for i, s in enumerate(sources):
# Start the thread to read frames from the video stream
# print('%g/%g: %s... ' % (i + 1, n, s), end='')
cap = cv2.VideoCapture(eval(s) if s.isnumeric() else s)
assert cap.isOpened(), 'Failed to open %s' % s
w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
h = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
fps = cap.get(cv2.CAP_PROP_FPS) % 100
self.ret, self.imgs[0] = cap.read() # guarantee first frame
thread = Thread(target=self.update, args=([0, cap]), daemon=True)
print(' success (%gx%g at %.2f FPS).' % (w, h, fps))
thread.start()
self.capture = cap
self.my_thread = thread
print('') # newline
# check for common shapes
s = np.stack([letterbox(x, new_shape=self.img_size)[0].shape for x in self.imgs], 0) # inference shapes
self.rect = np.unique(s, axis=0).shape[0] == 1 # rect inference if all shapes equal
if not self.rect:
print('WARNING: Different stream shapes detected. For optimal performance supply similarly-shaped streams.')
def update(self, index, cap):
# Read next stream frame in a daemon thread
n = 0
while cap.isOpened() and not self.stopFlag:
n += 1
# _, self.imgs[index] = cap.read()
cap.grab()
if n == 4: # read every 4th frame
_, self.imgs[index] = cap.retrieve()
n = 0
time.sleep(0.01) # wait time
def stop(self):
self.stopFlag = True
try:
# self.capture.release()
# self.my_thrsead.join()
print("stop thread!!")
except:
print("ERROR stopping thread!!")
def __iter__(self):
self.count = -1
return self
def __next__(self):
self.count += 1
img0 = self.imgs.copy()
if cv2.waitKey(1) == ord('q'): # q to quit
cv2.destroyAllWindows()
raise StopIteration
if not self.ret:
print("error!!!")
self.stop()
# Letterbox
img = [letterbox(x, new_shape=self.img_size, auto=self.rect)[0] for x in img0]
# Stack
img = np.stack(img, 0)
# Convert
img = img[:, :, :, ::-1].transpose(0, 3, 1, 2) # BGR to RGB, to bsx3x416x416
img = np.ascontiguousarray(img)
return self.sources, img, img0, None
def __len__(self):
return 0 # 1E12 frames = 32 streams at 30 FPS for 30 years
# def stop(self):
def clean_str(s):
# Cleans a string by replacing special characters with underscore _
return re.sub(pattern="[|##!¡·$€%&()=?¿^*;:,¨´><+]", repl="_", string=s)
def letterbox(img, new_shape=(640, 640), color=(114, 114, 114), auto=True, scaleFill=False, scaleup=True):
# Resize image to a 32-pixel-multiple rectangle https://github.com/ultralytics/yolov3/issues/232
shape = img.shape[:2] # current shape [height, width]
if isinstance(new_shape, int):
new_shape = (new_shape, new_shape)
# Scale ratio (new / old)
r = min(new_shape[0] / shape[0], new_shape[1] / shape[1])
if not scaleup: # only scale down, do not scale up (for better test mAP)
r = min(r, 1.0)
# Compute padding
ratio = r, r # width, height ratios
new_unpad = int(round(shape[1] * r)), int(round(shape[0] * r))
dw, dh = new_shape[1] - new_unpad[0], new_shape[0] - new_unpad[1] # wh padding
if auto: # minimum rectangle
dw, dh = np.mod(dw, 32), np.mod(dh, 32) # wh padding
elif scaleFill: # stretch
dw, dh = 0.0, 0.0
new_unpad = (new_shape[1], new_shape[0])
ratio = new_shape[1] / shape[1], new_shape[0] / shape[0] # width, height ratios
dw /= 2 # divide padding into 2 sides
dh /= 2
if shape[::-1] != new_unpad: # resize
img = cv2.resize(img, new_unpad, interpolation=cv2.INTER_LINEAR)
top, bottom = int(round(dh - 0.1)), int(round(dh + 0.1))
left, right = int(round(dw - 0.1)), int(round(dw + 0.1))
img = cv2.copyMakeBorder(img, top, bottom, left, right, cv2.BORDER_CONSTANT, value=color) # add border
return img, ratio, (dw, dh)
while cap.isOpened() and not self.stopFlag:
this line is especially important because
without this line the threads will be stacked and will have memory error
as the stack stacks up.
I am working on an experiment with plants in a pressure chamber. I need to be able to identify with a computer vision algorithm the exact moment when water starts to appear at the cut end of the stem. In the case of this video - taken from a USB microscope, this is the interval between 0:30 and 0:34 seconds, approximately.
I tried to use MOG, MOG2 and GMG as a background subtractor, and compare the histograms of each frame (using chi-squared, bhattacharyya, correlation), looking for changes that could be significant, however still without success. Is there a better alternative for this type of work?
Below, some code (made with the help of a friend)
import numpy as np
import sys
import time
import cv2
from matplotlib import pyplot as plt
video_filename = 'M20201022_004.mov'
capture = cv2.VideoCapture(video_filename)
#fgbg = cv2.bgsegm.createBackgroundSubtractorMOG()
fgbg = cv2.createBackgroundSubtractorMOG2()
#kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(3,3))
#fgbg = cv2.bgsegm.createBackgroundSubtractorGMG()
width = int(capture.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(capture.get(cv2.CAP_PROP_FRAME_HEIGHT))
frames_per_second = capture.get(cv2.CAP_PROP_FPS)
num_frames = int(capture.get(cv2.CAP_PROP_FRAME_COUNT))
print(' height: {}\n width: {}\n fps: {}\n num_frames: {}\n'.format(height, width,frames_per_second, num_frames))
frameCounter = 0
t = time.process_time()
dist_hist = 0 # distance between histograms
frame_hist = 0
time_hist = 0
#write file
file1 = open("resultado.txt","w")
if not capture.isOpened():
print("Could not open video")
print('frameCounter: {}'.format(frameCounter))
sys.exit(1)
while capture.isOpened():
success, frame = capture.read()
frameCounter += 1
# Test for read error
if not success:
print('Failed to read video - Video Capture EOF or Error')
print('frameCounter:{}'.format(frameCounter))
if frameCounter == num_frames + 1:
print('EOF found')
else:
print('error')
break
#sys.exit(1)
else:
if frameCounter % 1000 == 0:
print('type:{} size:{} dtype:{} len(shape):{} contador:{}'.format(type(frame),frame.size,frame.dtype,len(frame.shape),frameCounter))
if len(frame.shape) < 3: # grayscale
h, w = frame.shape
print('h:{} w:{}'.format(h, w))
else: # color image
h, w, ch = frame.shape
print('h:{} w:{} ch:{}'.format(h, w, ch))
fgmask = fgbg.apply(frame)
#fgmask = fgbg.apply(frame)
#fgmask = cv2.morphologyEx(fgmask, cv2.MORPH_OPEN, kernel)
# Initial histogram Test
if frameCounter == 1:
hist_initial = cv2.calcHist([fgmask], [0],None,[16],[0, 256])
# print('hist_initial:{}'.format(hist_initial))
#elapsed_time = time.process_time() - t
elapsed_time = frameCounter / frames_per_second
# Process Histogram
hist_process = cv2.calcHist([fgmask], [0],None,[16],[0, 256])
dist = cv2.compareHist(hist_initial, hist_process,cv2.HISTCMP_CHISQR)
str1 = str(frameCounter) + "," + str(dist) + "," + str(dist_hist) + "," + str(elapsed_time)
file1.write(str1)
file1.write("\n")
if dist > dist_hist: # Depending on compareHist method
dist_hist = dist
time_hist = elapsed_time
frame_hist = frameCounter
# Print line at image
strfmt = 'frame: {} elapsed_time: {:7.2f}'.format(frameCounter, elapsed_time)
cv2.putText(frame, strfmt, (0, 50),cv2.FONT_HERSHEY_COMPLEX_SMALL, 1, (0,0,255), 1, cv2.LINE_AA)
cv2.imshow('frame', frame)
cv2.imshow('fgmask', fgmask)
if cv2.waitKey(1) & 0xff == 27: # ESC pressed
break
print('---> frame:{} dist:{:10.6f} time:{:7.2f}'.format(frame_hist, dist_hist,time_hist))
capture.release()
cv2.destroyAllWindows()
file1.close()
Any help appreciated!
I'm using python 3.7.6 and openCV.
I want to display large size images(8K bmp) frame by frame, like animation.(But i can not make them as video. I have to preserve every data of pixels)
So i made image player using python and openCV, and it works well in usual window size(2~5K window), but as soon as i play it in fullscreen on 8K display, its frame rate drops to under 5 fps.
I tried with other image formats(such as jpeg, png), but as soon as enlarge window size, it work same with bmp.
i want to know
1) why its frame rate drops in large window?
2) how can i make image player that displaying images at least 15fps on 8K window.
here's code
import numpy as np
import cv2
import time
#variable setting
s=input('how many frames you want to play?(type in int.): ')
print(' display images in %sHz.' %s)
p=input('How many images you want to play?(type in int): ')
print(' program will read %s images.' %p)
t=input('what is the format of images?(0:png,1:bmp,2:jpg): ')
if t=='0':
t='png'
elif t=='1':
t='bmp'
elif t=='2':
t='jpg'
else:
t='png'
print(' image format is %s.' %t)
q=input('What type of display you want?(0: FULL, 1.NORMAL, 2: AUTO): ')
if q=='0':
cv2.namedWindow('test',cv2.WND_PROP_FULLSCREEN)
cv2.moveWindow('test',0,0)
cv2.setWindowProperty('test', cv2.WND_PROP_FULLSCREEN, cv2.WINDOW_FULLSCREEN)
print(' FULLSCREEN MODE.')
elif q=='1':
cv2.namedWindow('test',cv2.WND_PROP_FULLSCREEN)
cv2.moveWindow('test',0,0)
cv2.setWindowProperty('test', cv2.WND_PROP_FULLSCREEN, cv2.WINDOW_NORMAL)
print(' NORMAL MODE.')
elif q=='2':
cv2.namedWindow('test',cv2.WND_PROP_FULLSCREEN)
cv2.moveWindow('test',0,0)
cv2.setWindowProperty('test', cv2.WND_PROP_FULLSCREEN, cv2.WINDOW_AUTOSIZE)
print(' AUTOSIZE MODE.')
refresh_hz = int(s) #frequency of image playing
delay = (1/refresh_hz*1000)/1000
print('interval: %.2f s' %delay)
total_img = int(p) #total number of images
count = 0
flag = 0
start = time.time()
#image read
img = []
for i in range(1,total_img+1):
#r_image=("./source_image/%d.%s" %(i,t))
r_image=("./%s_img/%d.%s" %(t,i,t))
#r_image=("./img/%d.%s" %(i,t))
print('reading %dth image' %i)
temp = cv2.imread(r_image)
img.append(temp)
print('Completed to read %d images.' %total_img)
print('It will play %d images in %dHz.' %(total_img, refresh_hz))
print("If you want to quit, hit Escape. Thanks")
#Image Player
while True:
current = time.time()
a= current-start
if( a >= delay ):
cv2.imshow('test', img[count])
freq=1/a
print('interval: %.3f / freq : %.3f Hz' %(a, freq))
if(flag == 0):
count = count +1
if (count > total_img -2):
flag = 1
elif(flag == 1):
count=count-1
if (count < 1):
flag = 0
start = time.time()
k=cv2.waitKey(1)
if(k==27):
break
#Quit
cv2.destroyAllWindows()
In my code I am constantly grabbing frames from a camera to check if there is any human body present or not. whenever there is a human, crop the body and upload it on server. and keep doing this.
PROBLEM: Whenever I start a thread to upload photo to server my program execution stops and wait for the upload thread to finish. I don't want my program execution to stop and wait. I want it to run without stopping. I want to start a separate thread to upload photo that runs parallel, does its job without disturbing normal flow and finishes after it. it should do this every time there is a body detected.
# USAGE
# python detect.py --images images
# import the necessary packages
from __future__ import print_function
from imutils.object_detection import non_max_suppression
from imutils import paths
import numpy as np
import argparse
import imutils
import cv2
import time
import threading
import Queue
import multiprocessing
import requests
from poster.encode import multipart_encode
from poster.streaminghttp import register_openers
import urllib2
from urllib2 import Request, urlopen, URLError
import Queue
import urllib
import traceback
size = 2
i=0
#Queues to store data
queue_FACES = multiprocessing.Queue()
(im_width, im_height) = (112, 112)
# initialize the HOG descriptor/person detector
hog = cv2.HOGDescriptor()
hog.setSVMDetector(cv2.HOGDescriptor_getDefaultPeopleDetector())
# Capture Camera Stream
#webcam = cv2.VideoCapture('/home/irum/Desktop/WIN_20170529_09_53_13_Pro.mp4')
webcam = cv2.VideoCapture(0)
#h=4.27 w=4.29 AVG = 4.28
# Upload to server
def upload_internet(filename2,sampleFile,check_path1):
#print("upoading....")
filename2 = filename2+'.jpg'
#print (filename2)
register_openers()
datagen, headers = multipart_encode({"sampleFile": open(sampleFile), "name": filename2})
#request = urllib2.Request("http://videoupload.hopto.org:5000/api/Sync_log", datagen, headers)
request = urllib2.Request("http://videoupload.hopto.org:5002/api/Synclog", datagen, headers)
try:
#print ("***UPLOAD SERVER RESPONSE***")
response = urllib2.urlopen(request)
html=response.read()
print ("html ",html)
#resp = json.loads(html)
# with open('output_file.txt', "wb") as code: #CHANGE PATH
# code.write(curr_time+"\n"+html +"\n")
except URLError , e:
if hasattr(e, 'reason'):
#print ('We failed to reach a server.')
print ('Reason: ', e.reason)
elif hasattr(e, 'code'):
#print ('The server couldn\'t fulfill the request.')
print ('Error code: ', e.code)
except Exception:
print ('generic exception: ' + traceback.format_exc())
while True:
# read each frame
ret, frame = webcam.read()
# resize it
image = imutils.resize(frame, width=min(300, frame.shape[1]))
orig = image.copy()
# detect people in the frame
(rects, weights) = hog.detectMultiScale(image, winStride=(4, 4),
padding=(8, 8), scale=1.05)
# draw the original bounding boxes
for i in range(len(rects)):
body_i = rects[i]
(x, y, w, h) = [v * 1 for v in body_i]
cv2.rectangle(orig, (x, y), (x + w, y + h), (0, 0, 255), 2)
# apply non-maxima suppression
rects = np.array([[x, y, x + w, y + h] for (x, y, w, h) in rects])
pick = non_max_suppression(rects, probs=None, overlapThresh=0.65)
# draw the final bounding boxes
for i in range(len(rects)):
body_i = rects[i]
(xA, yA, xB, yB) = [int(v * 1) for v in body_i]
# rect on scaled image
cv2.rectangle(image, (xA, yA), (xB, yB), (0, 255, 0), 2)
# rects to map on original frame
(x1, y1, w1, h1) = [int(v * 4.28) for v in body_i]
cv2.rectangle(frame, (x1, y1), (w1, h1), (0, 45, 255), 2)
# Crop body from Original frame
body_big = frame[y1:y1+h1, x1:x1+w1]
# Save body
save_body_path = '/home/irum/Desktop/pedestrian-detection/BIG_BODY'
cur_date = (time.strftime("%Y-%m-%d"))
cur_time = (time.strftime("%H:%M:%S"))
new_pin =cur_date+"-"+cur_time
filename1 = 'BIG'
filename2 = str(filename1)+"-"+str(new_pin)
print ("filename2",filename2)
sampleFile = ('%s/%s.jpg' % (save_body_path, filename2))
print ("sampleFile",sampleFile)
cv2.imwrite('%s/%s.jpg' % (save_body_path, filename2), body_big)
# upload body
upload_process = threading.Thread(target=upload_internet(filename2,sampleFile,save_body_path))
upload_process.start()
# show the output images
cv2.imshow("Before NMS", orig)
cv2.imshow("After NMS", image)
cv2.imshow("BIG BODY", frame)
# cv2.imshow("FACE", body_big2)
key = cv2.waitKey(10)
if key == 27:
break
Correction:
Use cThread = threading.Thread( target= , args=() ) to define a
new thread instance
Use cThread.start() to launch it, of course you don't have join since your process is continuous.
simplified code so I could test-run it at my end:
import time
import threading
import multiprocessing
from time import sleep
def upload_internet(filename,sampleFile,check_path):
print ("//// WAITING FOR SERVER RESPONSE")
time.sleep(3)
print ("RECEIVED SERVER RESPONSE \\\\\\")
filename = "filename"
sampleFile = "sampleFile"
save_body_path = "save_body_path"
key = 1
while True:
rects = range(0,10)
# draw the original bounding boxes
range_len_rects = range(len(rects))
for i in range_len_rects:
print("Main starts")
rects = range(0,10)
thread_list = []
for i in range_len_rects:
# upload body
thread_list.append ( threading.Thread( target=upload_internet, args=( filename + "-" + str(i) ,sampleFile,save_body_path) ) )
thread_list[i].start()
print ("Exiting Launch Thread loop :"+ str(i) + "/" + str(range_len_rects[i]) )
print("Main sleep for 10 seconds")
time.sleep(10);
if key == 27:
break
PS: Remember the thread is not destroyed and you must ensure the upload_internet() doesn't stuck in memory for any reason, or you can control number of instance you have and set cap and manage zombie threads to avoid process crash and bad memory management
i am implementing a FTP upload with my python script. Everything works except for my ftp upload. I have used chmod to change the permissions of the folder that i have got my images and script in to chmod -R 777. And the permissions on the FTP server are all set at 777. Please note that ftpDir is intentionally left blank as this is the root folder for the account on the ftp server. I do not know what else i can do to fix this issue. 3
This is my error code that i get:
placeFile - Start FTP to ftp.brisbaneskycams.com
placeFile - ERROR FTP transfer Failed ...
Filename : /home/pi/pimotion/images/capture-20160503-044806.jpg
Error Msg: ['[Errno', '-2] Name or service not known']
Please Investigate Problem ...
This is the script:
#!/usr/bin/python
#
# Lightweight Motion Detection using python picamera libraries
# based on code from raspberry pi forum by user utpalc
# modified by Claude Pageau for this working example
# ------------------------------------------------------------
# original code on github https://github.com/pageauc/picamera-motion
# This is sample code that can be used for further development
verbose = True
if verbose:
print "Loading python libraries ....."
else:
print "verbose output has been disabled verbose=False"
import picamera
import picamera.array
import datetime
import time
from PIL import Image
from PIL import ImageFont
from PIL import ImageDraw
from fractions import Fraction
import ftplib
from ftplib import FTP
import os
#Constants
SECONDS2MICRO = 1000000 # Constant for converting Shutter Speed in Seconds to Microseconds
# User Customizable Settings
imageDir = "images"
imagePath = "/home/pi/pimotion/" + imageDir
imageNamePrefix = 'capture-' # Prefix for all image file names. Eg front-
imageWidth = 1980
imageHeight = 1080
imageVFlip = False # Flip image Vertically
imageHFlip = False # Flip image Horizontally
imagePreview = False
# FTP Server location variables
ftpOn = True
ftpServer = "ftphostname"
ftpDir = ""
ftpUser = "ftpusername"
ftpPass = "XXXXXXXXXX"
numberSequence = False
threshold = 10 # How Much pixel changes
sensitivity = 100 # How many pixels change
nightISO = 800
nightShutSpeed = 6 * SECONDS2MICRO # seconds times conversion to microseconds constant
# Advanced Settings not normally changed
testWidth = 100
testHeight = 75
def checkImagePath(imagedir):
# Find the path of this python script and set some global variables
mypath=os.path.abspath(__file__)
baseDir=mypath[0:mypath.rfind("/")+1]
baseFileName=mypath[mypath.rfind("/")+1:mypath.rfind(".")]
# Setup imagePath and create folder if it Does Not Exist.
imagePath = baseDir + imagedir # Where to save the images
# if imagePath does not exist create the folder
if not os.path.isdir(imagePath):
if verbose:
print "%s - Image Storage folder not found." % (progName)
print "%s - Creating image storage folder %s " % (progName, imagePath)
os.makedirs(imagePath)
return imagePath
def takeDayImage(imageWidth, imageHeight, filename):
if verbose:
print "takeDayImage - Working ....."
with picamera.PiCamera() as camera:
camera.resolution = (imageWidth, imageHeight)
# camera.rotation = cameraRotate #Note use imageVFlip and imageHFlip variables
if imagePreview:
camera.start_preview()
camera.vflip = imageVFlip
camera.hflip = imageHFlip
# Day Automatic Mode
camera.exposure_mode = 'auto'
camera.awb_mode = 'auto'
camera.capture(filename)
def placeFile(filepath):
path, filename = os.path.split(filepath)
os.chdir(path)
print filename
print path
if verbose:
print("placeFile - Start FTP to %s" % ftpServer )
try:
ftp = FTP(ftpServer)
ftp.login(user=ftpUser, passwd = ftpPass)
ftp.cwd(ftpDir)
ftp.storbinary('STOR ' + filename, open(filename, 'rb'))
ftp.quit()
if verbose:
print("placeFile - SUCCESSFUL FTP Transfer")
print(" Filename : %s " % (filepath))
except ftplib.all_errors as e:
errorcode_string = str(e).split(None, 1)
if verbose:
print("placeFile - ERROR FTP transfer Failed ...")
print(" Filename : %s " % (filepath))
print(" Error Msg: %s" % ( errorcode_string ))
print(" Please Investigate Problem ...")
def takeNightImage(imageWidth, imageHeight, filename):
if verbose:
print "takeNightImage - Working ....."
with picamera.PiCamera() as camera:
camera.resolution = (imageWidth, imageHeight)
if imagePreview:
camera.start_preview()
camera.vflip = imageVFlip
camera.hflip = imageHFlip
# Night time low light settings have long exposure times
# Settings for Low Light Conditions
# Set a frame rate of 1/6 fps, then set shutter
# speed to 6s and ISO to approx 800 per nightISO variable
camera.framerate = Fraction(1, 6)
camera.shutter_speed = nightShutSpeed
camera.exposure_mode = 'off'
camera.iso = nightISO
# Give the camera a good long time to measure AWB
# (you may wish to use fixed AWB instead)
time.sleep(10)
camera.capture(filename)
if verbose:
print "checkNightMode - Captured %s" % (filename)
return filename
def takeMotionImage(width, height, daymode):
with picamera.PiCamera() as camera:
time.sleep(1)
camera.resolution = (width, height)
with picamera.array.PiRGBArray(camera) as stream:
if daymode:
camera.exposure_mode = 'auto'
camera.awb_mode = 'auto'
else:
# Take Low Light image
# Set a framerate of 1/6 fps, then set shutter
# speed to 6s and ISO to 800
camera.framerate = Fraction(1, 6)
camera.shutter_speed = nightShutSpeed
camera.exposure_mode = 'off'
camera.iso = nightISO
# Give the camera a good long time to measure AWB
# (you may wish to use fixed AWB instead)
time.sleep( 10 )
camera.capture(stream, format='rgb')
return stream.array
def scanIfDay(width, height, daymode):
data1 = takeMotionImage(width, height, daymode)
while not motionFound:
data2 = takeMotionImage(width, height, daymode)
pCnt = 0L;
diffCount = 0L;
for w in range(0, width):
for h in range(0, height):
# get the diff of the pixel. Conversion to int
# is required to avoid unsigned short overflow.
diff = abs(int(data1[h][w][1]) - int(data2[h][w][1]))
if diff > threshold:
diffCount += 1
if diffCount > sensitivity:
break; #break outer loop.
if diffCount > sensitivity:
motionFound = True
else:
# print "Sum of all pixels=", pxCnt
data2 = data1
return motionFound
def scanMotion(width, height, daymode):
motionFound = False
data1 = takeMotionImage(width, height, daymode)
while not motionFound:
data2 = takeMotionImage(width, height, daymode)
diffCount = 0L;
for w in range(0, width):
for h in range(0, height):
# get the diff of the pixel. Conversion to int
# is required to avoid unsigned short overflow.
diff = abs(int(data1[h][w][1]) - int(data2[h][w][1]))
if diff > threshold:
diffCount += 1
if diffCount > sensitivity:
break; #break outer loop.
if diffCount > sensitivity:
motionFound = True
else:
data2 = data1
return motionFound
def getFileName(imagePath, imageNamePrefix, currentCount):
rightNow = datetime.datetime.now()
if numberSequence :
filename = imagePath + "/" + imageNamePrefix + str(currentCount) + ".jpg"
else:
filename = "%s/%s%04d%02d%02d-%02d%02d%02d.jpg" % ( imagePath, imageNamePrefix ,rightNow.year, rightNow.month, rightNow.day, rightNow.hour, rightNow.minute, rightNow.second)
return filename
def motionDetection():
print "Scanning for Motion threshold=%i sensitivity=%i ......" % (threshold, sensitivity)
isDay = True
currentCount= 1000
while True:
if scanMotion(testWidth, testHeight, isDay):
filename = getFileName(imagePath, imageNamePrefix, currentCount)
if numberSequence:
currentCount += 1
if isDay:
takeDayImage( imageWidth, imageHeight, filename )
else:
takeNightImage( imageWidth, imageHeight, filename )
if verbose:
print("MotionDetection - Saved %s" % filename)
if ftpOn:
placeFile(filename)
if __name__ == '__main__':
try:
motionDetection()
finally:
print ""
print "+++++++++++++++"
print "Exiting Program"
print "+++++++++++++++"
print ""