GPIO.output(21, GPIO.HIGH) def updateValue(i, value): if value[i - 1] == 0: GPIO.output(26, GPIO.HIGH) GPIO.output(19, GPIO.LOW) if value[i - 1] == 1: GPIO.output(26, GPIO.LOW) GPIO.output(19, GPIO.HIGH) camera = PiCamera() camera.resolution = (320, 240) camera.framerate = 20 rawCapture = PiRGBArray(camera) hand_cascade = cv2.CascadeClassifier('hand.xml') startx, starty = -1, -1 endx, endy = -1, -1 counter = 0 diffx, diffy = 1, 1 channel = [16, 20, 21] # GPIO channel array value = [0, 0, 0] i = 1 time.sleep(0.5) for frame in camera.capture_continuous(rawCapture, format="bgr", use_video_port=True): # grab the raw NumPy array representing the image, then initialize the timestamp
from picamera.array import PiRGBArray from picamera import PiCamera import time from imutils.perspective import four_point_transform #from imutils import contours #import imutils cameraResolution = (320, 240) # initialize the camera and grab a reference to the raw camera capture camera = PiCamera() camera.resolution = cameraResolution camera.framerate = 32 camera.brightness = 60 camera.rotation = 180 rawCapture = PiRGBArray(camera, size=cameraResolution) # allow the camera to warmup time.sleep(2) def findTrafficSign(): ''' This function find blobs with blue color on the image. After blobs were found it detects the largest square blob, that must be the sign. ''' # define range HSV for blue color of the traffic sign lower_blue = np.array([90, 80, 50]) upper_blue = np.array([110, 255, 255])
def main(name): # import the cascades face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml') eye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml') # load the webcam feed #capture = cv2.VideoCapture(0) camera = PiCamera() camera.resolution = (640, 480) camera.framerate = 32 rawCapture = PiRGBArray(camera, size=(640, 480)) # counter for picture counter = 0 time.sleep(0.1) for frame in camera.capture_continuous(rawCapture, format="bgr", use_video_port=True): img = frame.array gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) #print capture faces = face_cascade.detectMultiScale(img, 1.3, 5) # array with found faces for (x, y, w, h) in faces: # draw rectangles # img = where to draw # next 2 args are start and end points of rectangle # next arg is color # final arg is line width cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0), 2) cv2.putText(img, 'Face', (x, y), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 255), 1, cv2.CV_AA) # region of img, dont want to find eyes outside face roi_gray = gray[y:y + h, x:x + h] # roi_color = img[y:y+h, x:x+h] # only show the face box (row, column of img numpy array to be displayed) img = roi_gray img = cv2.equalizeHist(img) # resize the camera feed cv2.imshow('mode 1', img) rawCapture.seek(0) rawCapture.truncate() # # resize the camera feed # cv2.namedWindow('Do not read', cv2.WINDOW_NORMAL) # cv2.imshow('Do not read', img) # to save img to file with esc key k = cv2.waitKey(30) & 0xff if k == 27: # unique_filename = uuid.uuid4() # unique_filename = str(unique_filename) # print "Saving file " + unique_filename im = Image.fromarray(img) im = im.resize((92, 112), PIL.Image.ANTIALIAS) filename = 'subject' + str(name) + '.' + str(counter) + '.jpeg' print 'saving file ' + filename im.save('train_faces2/' + filename) counter += 1 if k == 108: # l camera.close() cv2.destroyAllWindows() return
from picamera.array import PiRGBArray from picamera import PiCamera image_size = 64 cropped_size = 380 recognition_ratio = 10 res = (640, 480) fps = 30 # initialize the cam camera = PiCamera() camera.resolution = res camera.framerate = fps rawCapture = PiRGBArray(camera, size=res) # allow the camera to warmup time.sleep(0.1) # capture frames from the camera for frame in camera.capture_continuous(rawCapture, format='bgr', use_video_port=True): # current frame as numpy array img = frame.array img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # img_resized = resize_img(img_gray, img_size)
GPIO.setup(enB,GPIO.OUT) p2=GPIO.PWM(enB,1000) ####################motor start p.start(15) p2.start(15) print("\n") print("working properly by camera.....") print("\n") #camera camera = picamera.PiCamera() camera.resolution =(192,108) camera.framerate = 20 rawCapture = PiRGBArray(camera,size=(192,108)) time.sleep(0.1) for frame in camera.capture_continuous(rawCapture, format="bgr", use_video_port=True): # Display camera input image = frame.array cv2.imshow('img',image) # Create key to break for loop key = cv2.waitKey(1) & 0xFF # convert to grayscale, gaussian blur, and threshold gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) blur = cv2.GaussianBlur(gray,(5,5),0) ret,thresh1 = cv2.threshold(blur,100,255,cv2.THRESH_BINARY_INV)
import sys # import the necessary packages for tracking from imutils import contours import imutils from Functions.Blocking import Blocking Block = Blocking() # http://picamera.readthedocs.io/en/latest/fov.html # initialize the Pi camera and grab a reference to the raw camera capture camera = PiCamera() camera.resolution = (1648, 928) #Maximum Resolution with full FOV camera.framerate = 40 # Maximum Frame Rate with this resolution rawCapture = PiRGBArray(camera, size=(1648, 928)) # allow the camera to warmup. time.sleep(0.1) class UART_Thread(threading.Thread): def __init__(self, q_Control_Serial_Write, q_Data_is_Send, q_Control_Uart_Main): ''' Constructor. of UART Thread ''' threading.Thread.__init__(self) self.daemon = True self.q_Control_Serial_Write = q_Control_Serial_Write self.q_Data_is_Send = q_Data_is_Send self.q_Control_Uart_Main = q_Control_Uart_Main
import imutils import numpy as np cascPath = "haarcascade_frontalface_default.xml" font = cv2.FONT_HERSHEY_SIMPLEX faceCascade = cv2.CascadeClassifier(cascPath) casc_smile_path = "haarcascade_smile.xml" smile_cascade = cv2.CascadeClassifier(casc_smile_path) # initialize the camera and grab a reference to the raw camera capture camera = PiCamera() camera.resolution = (260, 220) camera.framerate = 40 rawCapture = PiRGBArray(camera, size=(260, 220)) # allow the camera to warmup time.sleep(0.1) # capture frames from the camera for frame in camera.capture_continuous(rawCapture, format="bgr", use_video_port=True): # grab the raw NumPy array representing the image, then initialize the timestamp # and occupied/unoccupied text image = frame.array gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # Detect faces in the image
import imutils import time import cv2 # video capturing count = 0 frame_width = 640 frame_height = 480 # if the video argument is None, then we are reading from webcam print("Using raspi camera...") # initialize the camera and grab a reference to the raw camera capture camera = PiCamera() camera.resolution = (frame_width, frame_height) #camera.framerate = 32 rawCapture = PiRGBArray(camera, size=(frame_width, frame_height)) time.sleep(2.0) # initialize the first frame in the video stream firstFrame = None print("[+] Starting security camera...") for frame in camera.capture_continuous(rawCapture, format="bgr", use_video_port=True): rawCapture.truncate(0) # grab the current frame and initialize the occupied/unoccupied text frame = frame.array frame = frame if args.get("video", None) is None else frame[1]
from picamera.array import PiRGBArray from picamera import PiCamera import math import time import cv2 import numpy as np import os, sys from LaneDetection import LaneDetection from CarControl import CarControl from ObstacleDetection import ObstacleDetection from ModeView import ModeView camera = PiCamera() camera.resolution = (960, 540) camera.framerate = 15 rawCapture = PiRGBArray(camera, size=(960, 540)) time.sleep(0.1) GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) laneDetection = LaneDetection() carControl = CarControl() modeView = ModeView() obstacleDetection = ObstacleDetection() backLeft = [0, 0, 0, 0] backRight = [0, 0, 0, 0] vp_slope = [-1, backLeft, backRight] img2 = np.zeros((540, 960, 3), np.uint8)
x1 = x4 = int(bbox_x1 - mdl_dims / 2) #Right - X2 x2 = x3 = int(bbox_x2 - mdl_dims / 2) #Upper - Y1 y1 = y2 = int(-bbox_y1 + mdl_dims / 2) #Lower - Y2 y3 = y4 = int(-bbox_y2 + mdl_dims / 2) z = 1 bbox_vertices = [[x1, y1, z], [x2, y2, z], [x3, y3, z], [x4, y4, z]] return bbox_vertices with picamera.PiCamera() as camera: camera.resolution = (preview_W, preview_H) camera.framerate = max_fps rgb = PiRGBArray(camera, size=camera.resolution * 3) _, width, height, channels = engine.get_input_tensor_shape() camera.start_preview(fullscreen=False, layer=0, window=(preview_mid_X, preview_mid_Y, preview_W, preview_H)) try: while DISPLAY.loop_running(): stream = io.BytesIO() camera.capture(stream, use_video_port=True, format='rgb') stream.truncate() stream.seek(0) input = np.frombuffer(stream.getvalue(), dtype=np.uint8) stream.close() results = engine.DetectWithInputTensor(input, top_k=max_obj) ms = str(int(elapsed_ms * 1000)) + "ms"
def __init__(self,piCamera): piCamera.resolution = (304,304) piCamera.framerate =32 self.__piCamera = piCamera self.__rawCapture =PiRGBArray(piCamera,size=(304,304))
from detect_rgb3 import detect import serial import numpy as np import os port = '/dev/ttyACM0' ser = serial.Serial(port, 115200, timeout=2) X_RESOLUTION = 1280 Y_RESOLUTION = 960 # Initialize the camera and grab a reference to the raw camera capture camera = PiCamera() camera.resolution = (X_RESOLUTION, Y_RESOLUTION) camera.framerate = 5 rawCapture = PiRGBArray(camera, size=(X_RESOLUTION, Y_RESOLUTION)) # Allow camera to warmup time.sleep(0.1) i = 0 def speed(left, right): motor_control = "m " + str(int(left)) + " " + str(int(right)) ser.write(motor_control.encode()) test = 0 folder = 'test_' + str(test) if not os.path.isdir(folder): os.mkdir(folder)
import numpy as np import io from picamera.array import PiRGBArray from picamera import PiCamera from PIL import Image as Img from constants import * #set up camera and wait small bit of time for it to initialize camera = PiCamera() sleep(0.1) #flip horizontally camera.hflip = True #sets up a stream to convert from the camera input to OpenCV object later stream = PiRGBArray(camera) #generates the overlay object with appropriate padding #can specify layer of overlay - defaults to 4 def generate_overlay(img, layer=4): print(img.size) pad = Img.new('RGB', ( ((img.size[0] + 31) // 32) * 32, ((img.size[1] + 15) // 16) * 16, )) pad.paste(img, (0, 0)) o = camera.add_overlay(pad.tobytes(), size=pad.size) o.alpha = 32 o.layer = layer return o
return frame #### Initialize camera and perform object detection #### # The camera has to be set up and used differently depending on if it's a # Picamera or USB webcam. ### Picamera ### if camera_type == 'picamera': # Initialize Picamera and grab reference to the raw capture camera = PiCamera() camera.resolution = (IM_WIDTH, IM_HEIGHT) camera.framerate = 10 rawCapture = PiRGBArray(camera, size=(IM_WIDTH, IM_HEIGHT)) rawCapture.truncate(0) # Continuously capture frames and perform object detection on them for frame1 in camera.capture_continuous(rawCapture, format="bgr", use_video_port=True): t1 = cv2.getTickCount() # Acquire frame and expand frame dimensions to have shape: [1, None, None, 3] # i.e. a single-column array, where each item in the column has the pixel RGB value frame = frame1.array frame.setflags(write=1) # Pass frame into pet detection function
print("Görüntü alınıyor...") # Kamera kutuphanesinden bir nesne al ve kamera degiskenine ata kamera = PiCamera() # Kayıt/İşlem çözünürlüğü kamera.resolution = (sbt.KAMERA_COZUNURLUGU[0], sbt.KAMERA_COZUNURLUGU[1]) # Kameranin saniyedeki resim sayisini 50 olarak ayarla kamera.framerate = 50 # # Kamera kablo baglantisindan dolayi ters durdugu ve goruntu ters gozukecegi icin goruntuyu ters cevir # kamera.vflip = True # Resimleri tutmak icin bellekte yer ac resimBellegi = PiRGBArray(kamera, size=(sbt.KAMERA_COZUNURLUGU[0], sbt.KAMERA_COZUNURLUGU[1])) # Kameranin hazir olmasi icin biraz bekle time.sleep(0.1) print("Video kaydı için hazırlıklar yapılıyor...") # Video kaydı için kayitTime = time.strftime("%Y-%m-%d-%H-%M") fourcc = cv2.VideoWriter_fourcc(*'XVID') temizKayit = cv2.VideoWriter('./Medya/Kayitlar/' + kayitTime + 'temizKayit.avi', fourcc, 10.0, (sbt.KAMERA_COZUNURLUGU[0], sbt.KAMERA_COZUNURLUGU[1])) duvarKayit = cv2.VideoWriter('./Medya/Kayitlar/' + kayitTime + 'duvarKayit.avi', fourcc, 10.0, (sbt.CV_COZUNURLUGU[0], sbt.CV_COZUNURLUGU[1])) gemiKayit = cv2.VideoWriter('./Medya/Kayitlar/' + kayitTime + 'gemiKayit.avi', fourcc, 10.0, (sbt.CV_COZUNURLUGU[0], sbt.CV_COZUNURLUGU[1])) kapiKayit = cv2.VideoWriter('./Medya/Kayitlar/' + kayitTime + 'kapiKayit.avi', fourcc, 10.0, (sbt.CV_COZUNURLUGU[0], sbt.CV_COZUNURLUGU[1])) surKayit = cv2.VideoWriter('./Medya/Kayitlar/' + kayitTime + 'surKayit.avi', fourcc, 10.0, (sbt.CV_COZUNURLUGU[0], sbt.CV_COZUNURLUGU[1])) print("Görevlere hazırlanılıyor...")
def map(x, in_min, in_max, out_min, out_max): maps = ((x - in_max) * (out_max - out_min) / (in_max - in_min) + out_min + 10) return maps kp = 100 servo1 = 21 servo2 = 20 deltadt = 0.1 dt1 = 4 dt2 = 7 rp.setmode(rp.BCM) rp.setwarnings(False) rp.setup(servo1, rp.OUT) rp.setup(servo2, rp.OUT) pwm1 = rp.PWM(servo1, 50) pwm2 = rp.PWM(servo2, 50) pwm1.start(4) pwm2.start(2) webcam = PiCamera() webcam.resolution = (640, 480) webcam.framerate = 90 video = PiRGBArray(webcam, size=(640, 480)) pwm2.ChangeDutyCycle(2) for i in range(2, 12, 1): #pwm1.ChangeDutyCycle(dty) pwm2.ChangeDutyCycle(i) sleep(1)
fps = 30 logOffset = 3 # Skip this number of datapoints while logging # Create MP4 video file at 720p 30fps fourcc = cv2.VideoWriter_fourcc(*'mp4v') out = cv2.VideoWriter('output.mp4', fourcc, fps, resolution) # Create file to log data f = open('PiCameraTestData.txt', 'a') # Initialize the Raspberry Pi camera camera = PiCamera() camera.resolution = (1280, 720) camera.framerate = 30 rawCapture = PiRGBArray(camera, size=(1280, 720)) minHSV = np.array([40, 20, 25]) maxHSV = np.array([100, 180, 185]) # Framerate cumulative moving average cmaFramerate = 0 # Number of desired datapoints to log desiredDataPoints = 200 i = -logOffset start = 0 stop = 0 for frame in camera.capture_continuous(rawCapture,
import numpy as np import tensorflow as tf import time model = tf.keras.models.load_model('digits_model.h5') SZ = 28 frame_width = 300 frame_height = 300 frame_resolution = [frame_width, frame_height] frame_rate = 16 margin = 30 # initialize the camera and grab a reference to the raw camera capture camera = PiCamera() camera.resolution = frame_resolution camera.framerate = frame_rate rawCapture = PiRGBArray(camera, size=(frame_resolution)) # allow the camera to warmup time.sleep(0.1) # capture frames from the camera for frame in camera.capture_continuous(rawCapture, format="bgr", use_video_port=True): # grab the raw NumPy array representing the image image = frame.array # hsv transform - value = gray image hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV) hue, saturation, value = cv2.split(hsv) # kernel to use for morphological operations kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))
# client warnings.filterwarnings("ignore") conf = json.load(open(args["conf"])) client = None # check to see if the Dropbox should be used if conf["use_dropbox"]: # connect to dropbox and start the session authorization process client = dropbox.Dropbox(conf["dropbox_access_token"]) print("[SUCCESS] dropbox account linked") # initialize the camera and grab a reference to the raw camera capture camera = PiCamera() camera.resolution = tuple(conf["resolution"]) camera.framerate = conf["fps"] rawCapture = PiRGBArray(camera, size=tuple(conf["resolution"])) # allow the camera to warmup, then initialize the average frame, last # uploaded timestamp, and frame motion counter print("[INFO] warming up...") time.sleep(conf["camera_warmup_time"]) avg = None lastUploaded = datetime.datetime.now() motionCounter = 0 # capture frames from the camera for f in camera.capture_continuous(rawCapture, format="bgr", use_video_port=True): # grab the raw NumPy array representing the image and initialize # the timestamp and occupied/unoccupied text frame = f.array timestamp = datetime.datetime.now()
import cv2 import numpy # import the necessary packages from picamera.array import PiRGBArray from picamera import PiCamera import time print("123") #initialise the camera and grab a reference to raw camera capture camera = PiCamera() print("123") camera.resolution = (800, 600) rawCapture = PiRGBArray(camera, size=(800, 600)) time.sleep(0.1) print(123) while (1): print("123") # allow the camera to warmup time.sleep(0.1) print("456") # grab an image from the camera camera.capture(rawCapture, format="bgr") camera.capture("foo.jpg") frame = rawCapture.array # display the image on screen and wait for a keypress cv2.imshow("Image", frame) cv2.waitKey(8000) cv2.destroyAllWindows() camera.close()
from picamera import PiCamera import cv2 import time import numpy import stepper RES_CONST = 1 face_cascade = cv2.CascadeClassifier( "/usr/local/lib/python3.7/dist-packages/cv2/data/haarcascade_frontalface_default.xml" ) camera = PiCamera() camera.resolution = (640 * RES_CONST, 480 * RES_CONST) camera.framerate = 50 rawCapture = PiRGBArray(camera, size=(640 * RES_CONST, 480 * RES_CONST)) time.sleep(0.1) for image in camera.capture_continuous(rawCapture, format="bgr", use_video_port=True): frame = image.array #frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) faces = face_cascade.detectMultiScale(frame, scaleFactor=1.25, minNeighbors=5) if len(faces) > 0:
# Pic Properties picWidth = 640 picHeight = 480 framerate = 32 # Camera FOV hfov = 62.2 vfov = 48.8 # initialize the camera and grab a reference to the raw camera capture camera = PiCamera() camera.resolution = (picWidth, picHeight) camera.framerate = framerate camera.vflip = True rawCapture = PiRGBArray(camera, size=(picWidth, picHeight)) # allow the camera to warmup time.sleep(0.1) # capture frames from the camera for f in camera.capture_continuous(rawCapture, format="bgr", use_video_port=True): # grab the raw NumPy array representing the image, then initialize the timestamp # and occupied/unoccupied text frame = f.array # Find the lightSources in the unwarped image, and label them lightSources = findLightSources(frame, 230) # Threshold of 200 (arbitrary, needs experimentation) lightLoc = [] angles = [] trueAngles = []
widths = 440 heigths = 280 resX = 6 resY = 6 count = 0 imc = 0 hue = 0 sat = 0 val = 0 camera = PiCamera() camera.resolution = (widths, heigths) camera.framerate = 32 camera.hflip = True rawCapture = PiRGBArray(camera, size=(widths, heigths)) time.sleep(0.1) def closest_colour(requested_colour): min_colours = {} for key, name in webcolors.css3_hex_to_names.items(): r_c, g_c, b_c = webcolors.hex_to_rgb(key) rd = (r_c - requested_colour[0]) ** 2 gd = (g_c - requested_colour[1]) ** 2 bd = (b_c - requested_colour[2]) ** 2 min_colours[(rd + gd + bd)] = name return min_colours[min(min_colours.keys())] def dec_conv(x): return format(x, '03d')
def main_code(): RELAY = 17 gpio.setmode(gpio.BCM) gpio.setup(RELAY, gpio.OUT, initial=gpio.LOW) camera = PiCamera() camera.resolution = (640, 480) camera.framerate = 32 rawCapture = PiRGBArray(camera, size=(640, 480)) faceCascade = cv2.CascadeClassifier("haarcascade_frontalface_default.xml") eyesCascade = cv2.CascadeClassifier("haarcascade_eye_tree_eyeglasses.xml") time.sleep(0.1) c = 30 for frame in camera.capture_continuous(rawCapture, format="bgr", use_video_port=True): image = frame.array gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) faces = faceCascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5, minSize=(50, 50)) for (x, y, w, h) in faces: cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2) roi_gray = gray[y:y + h, x:x + w] roi_color = image[y:y + h, x:x + w] eyes = eyesCascade.detectMultiScale(roi_gray) for (ex, ey, ew, eh) in eyes: #print(eyes) cv2.rectangle(roi_color, (ex, ey), (ex + ew, ey + eh), (100, 255, 255), 2) if len(faces) >= 1 and len(eyes) >= 2: # cv2.putText(image, 'WARNING!', (10, 500), cv2.FONT_HERSHEY_SIMPLEX, 4, (255, 255, 255), 2) c += 1 if c >= 30: c = 30 print("off ", c) gpio.output(RELAY, False) else: gpio.output(RELAY, True) c -= 1 if c <= 0: c = 0 print("on ", c) gpio.output(RELAY, True) location = get_location( "https://parna-tech-gvp.000webhostapp.com/get_text.php" ) mess = "DRIVER IS SLEEPING AT POSITION $/maps.google.com/?q=" + str( location[0]) + "," + str(location[1]) resp, code = sendSMS( 'eUsxYafnBc0-FVAQyyMIBL4sXtGxz7WsFppmfolVqN', '919052687894', 'TXTLCL', mess) print(resp) #cv2.imshow("Frame", image) key = cv2.waitKey(1) & 0xFF rawCapture.truncate(0) if key == ord("q"): break gpio.output(RELAY, False) gpio.cleanup() cv2.destroyAllWindows()