Reading camera input from /dev/video0 in python or c - python

I want to read from the file /dev/video0 either through c or python,and store the incoming bytes in a different file.
Here is my c code:
#include<stdio.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
int main()
{
int fd,wfd;
fd=open("/dev/video0",O_RDONLY);
wfd=open("image",O_RDWR|O_CREAT|O_APPEND,S_IRWXU);
if(fd==-1)
perror("open");
while(1)
{
char buffer[50];
int rd;
rd=read(fd,buffer,50);
write(wfd,buffer,rd);
}
return 0;
}
When i run this code and after some time terminate the program nothing happens except a file name "image" is generated which is usual.
This is my python code:
image=open("/dev/video0","rb")
image.read()
and this is my error when my run this snippet:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IOError: [Errno 22] Invalid argument
I want to know how to do this using pure c or python code.Please no external library suggestions.

It's not so easy.
Most cameras won't work in read/write mode. You need to use Streaming I/O mode - for example memory mapping.
You need to set pixel format - YUYV/RGB/MJPEG, bytes per pixel, resolution.
You have to start grabbing, read and save at least one frame.

Further to my comment, here's an example of displaying a video stream from video on disk (see documentation):
import numpy as np
import cv2
video = "../videos/short.avi"
video_capture = cv2.VideoCapture(video)
while(True):
# Capture frame-by-frame
ret, frame = video_capture.read()
# Our operations on the frame comes here
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# Display the resulting frame
cv2.imshow('frame',gray)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# When everything's done, release the capture
video_capture.release()
cv2.destroyAllWindows()

Related

Cannot retrieve data from firebase '400 Bad Request'

I trying to retrieve data from firebase but it give me this error
Fatal error: Uncaught GuzzleHttp\Exception\ClientException: Client error: GET https://linkfirebase.firebasedatabase.app/GSBACILLI5%0A resulted in a 400 Bad Request response.
the reference is GSBACILLI5, but why the path to request data is GSBACILLI5%0A?
Btw, GSBACILLI5 is decode from QR code using webcam in python, did it give any problem to the path?
This is my code to call python program in PHP
$commandString = "python trackqr3.py";
$outpy=popen($commandString, 'r');
$contents = '';
#while (!feof($outpy)) {
foreach ((array)$outpy as $outpy){
$contents .= fread($outpy, 8192);
}
And this is my python script
import cv2
def capture():
# initialize the cv2 QRCode detector
detector = cv2.QRCodeDetector()
while True:
_, img = cap.read()
# detect and decode
data, bbox, _ = detector.detectAndDecode(img)
# check if there is a QRCode in the image
if data:
a=data
print(a)
return a
#break
cv2.imshow("QRCODEscanner", img)
#if cv2.waitKey(1) == ord("q"):
# break
cv2.waitKey(1)
cap = cv2.VideoCapture(0,cv2.CAP_DSHOW)
id=capture()
cap.release()
#print('ID:',id)
cv2.destroyAllWindows()
%0A means new line (Enter). Code hex(ord("\n")) gives 0A.
You send reference using print() but print() automatically add new line at the end of string.
You have to use end="" to skip new line
print(a, end="")
OR in PHP you should remove/strip this new line.
But I don't remeber what function in PHP it needs.

OpenCV; Read Camera on macOS; TypeError

I try to run a camera reading code in macOS. Here is my code:
import cv2
from pyzbar.pyzbar import decode
import os
os.system("clear")
cap = cv2.VideoCapture(0)
cap.set(3 , 640)
cap.set(4 , 480)
while True:
success, img = cap.read()
for barcode in decode(img):
print(barcode.data)
print(barcode.rect)
x = barcode.data.decode('utf-8')
print(x)
cv2.imshow('Result', img)
cv2.waitKey(1)
This is current error:
Traceback (most recent call last):
File "/Users/username/Documents/Pyzbar Lesson 2.py", line 21, in <module>
for barcode in decode(img):
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/pyzbar/pyzbar.py", line 207, in decode
pixels, width, height = _pixel_data(image)
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/pyzbar/pyzbar.py", line 173, in _pixel_data
pixels, width, height = image
TypeError: cannot unpack non-iterable NoneType object
Please, share if I miss anything or other error in the code.
Thanks.
This code works fine on my Windows machine (after changing 'clear' to 'cls' of course).
You're getting a Type Error because decode is trying to operate on a None type. In line 21 you call for barcode in decode(img). Here it is img that is 'None` and since decode cannot handle 'None' you get the error.
I suspect that your hardware is not cooperating properly. This could be due to your camera access preferences. You can use the cap.isOpen() and cap.isValid() checks to add an additional layer of trouble shooting.
I FINALLY FOUND THE ANSWER
Apparently, for some macOS users, having 'cap.set()' in your code would give you errors. But after removing it, it works perfectly
'''
import cv2
from pyzbar.pyzbar import decode
import os
os.system("clear")
cap = cv2.VideoCapture(0)
while True:
success, img = cap.read()
if not success:
break
for barcode in decode(img):
print(barcode.data)
print(barcode.rect)
x = barcode.data.decode('utf-8')
print(x)
cv2.imshow('Result', img)
cv2.waitKey(1)
'''

Python OpenCV Camera Error

For some reason, I cannot read camera video data using OpenCV and Python 3.
Here is the code I am using:
import cv2
import numpy as np
cap = cv2.VideoCapture(0)
while(1):
_, frame = cap.read()
cv2.imshow('frame',frame)
k = cv2.waitKey(5) & 0xFF
if k == 27:
break
cap.release()
cv2.destroyAllWindows()
This code returns the following error:
Traceback (most recent call last):
File "C:\Path\To\File\VideoTest.py", line 10, in <module>
cv2.imshow('frame',frame)
cv2.error: D:\Build\OpenCV\opencv-3.3.1\modules\highgui\src\window.cpp:339: error: (-215) size.width>0 && size.height>0 in function cv::imshow
The computer is running Windows Server 2012 R2 and has one USB webcam permanently in use in addition to the new one I am trying to read data from. I have tried changing the line cap = cv2.VideoCapture(0) to cap = cv2.VideoCapture(1) and had an identical error.
I tried replicating the error on my laptop using the same code and USB webcam, but it worked perfectly and I was able to stream the video.
**EDIT**
To debug, I ran the following program line-by-line in the Python shell.
import numpy as np
import cv2
cap = cv2.VideoCapture(0)
print(cap.read())
cap = cv2.VideoCapture(1)
print(cap.read())
The code outputted (False, None) twice.

I need hikvision camera which has ip 20.0.0.14 and user name/password is admin/12345 to run by python code

I need hikvision camera which has ip 20.0.0.14 and user name/password is admin/12345 to run by python code
the original camera code is
import cv2.cv as cv
import time
cv.NamedWindow("camera", 1)
capture = cv.CaptureFromCAM(0)
while True:
img = cv.QueryFrame(capture)
cv.ShowImage("camera", img)
if cv.WaitKey(10) == 27:
break
cv.DestroyAllWindows()
i need help please
Here's the solution when using OpenCV3. In your sample code, you are not only not using the OpenCV2 interface, but you are accessing the very old cv (prior to OpenCV 2) interface. So my first suggestion is to get a current install of OpenCV working.
Possible source of rtsp urls for use with hikvision cameras:
https://www.ispyconnect.com/man.aspx?n=Hikvision
import cv2
# Note the following is the typical rtsp url for streaming from an ip cam
# source = "rtsp://user:password#ipaddress:port/<camera specific stuff>"
# Each manufacturer is different. For my alibi cameras, this would be
# a valid url to use with the info you provided.
source = "rtsp://admin:12345#20.0.0.14//Streaming/Channels/2"
cap = cv2.VideoCapture(source)
ok_flag = True
while ok_flag:
(ok_flag, img) = cap.read()
if not ok_flag: break
cv2.imshow("some window", img)
if cv2.waitKey(10) == 27:
break
cv2.destroyAllWindows()
Also note that this code works the same if the source is the path to a valid video file (like an .avi), or for a web camera (in which case you pass the integer number of the webcam, like 0).
Another error in your post is the cv.CaptureFromCAM(0), which would be capturing from the first webcam installed on the computer, not an ip stream.

2 webcam feed doesn't work opencv

I'm using ubuntu 13.10 along with opencv 2.4.9 with python 2.7.
I have written the following code but it seems to fails on runtime.
import cv2
c1=cv2.VideoCapture(2) #camera id
c2=cv2.VideoCapture(1) #camera id
while(True):
ret,frame = c1.read()
ret,frame2 = c2.read()
frame = cv2.cvtColor(frame,0)
frame2 = cv2.cvtColor(frame2,0)
cv2.imshow('frame',frame)
cv2.imshow('frame2',frame2)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
c1.release()
c2.release()
cv2.destroyAllWindows()
But on running this in Ubuntu i get the following error :
VIDIOC_QUERYMENU: Invalid argument
libv4l2: error turning on stream: Invalid argument
VIDIOC_STREAMON: Invalid argument
OpenCV Error: Assertion failed (scn == 3 || scn == 4) in cvtColor, file
/build/buildd/opencv-2.4.5+dfsg/modules/imgproc/src/color.cpp, line 3358
Traceback (most recent call last):
File "/home/bini/KV/IP_Proj/webcam basics opencv.py", line 8, in <module>
frame2 = cv2.cvtColor(frame2,0)
cv2.error: /build/buildd/opencv-2.4.5+dfsg/modules/imgproc/src/color.cpp:3358: error:
(-215) scn == 3 || scn == 4 in function cvtColor
The same code used to work fine on windows.
Can someone help me please as to why is this occuring..??? i have on idea.
Thanks in advance
For linux,if you're using 1 camera , at first you must change your camera id to 0 , but it seems that you want use 2 camera , this is because the resolution, framerate and protocol used by your cameras overloads the USB connection so read this link! also this is a base code for connect and use linux webcam:
import numpy as np
import cv2
cap = cv2.VideoCapture(0)
#set the width and height, and UNSUCCESSFULLY set the exposure time
cap.set(3,1080)
cap.set(4,1024)
cap.set(15, 0.1)
while True:
ret, img = cap.read()
cv2.imshow("input",img)
key = cv2.waitKey(10)
if key == 27:
break
cv2.destroyAllWindows()
cv2.VideoCapture(0).release()
One (or both) of your cameras isn't initializing correctly. I just ran your code on my machine (Ubuntu 14.04) and both frames come up showing live views from my two connected cameras. Can you view both cameras in cheese or guvcview?
I do get a bunch of these messages:
VIDIOC_QUERYMENU: Invalid argument
errors but neither of these:
libv4l2: error turning on stream: Invalid argument
VIDIOC_STREAMON: Invalid argument

Categories

Resources