OpenCV Video Capture not working for Android | Kivy, Buildozer - python

I am building an App which got several video filters. But the App is not working on Android cause => capture = cv.VideoCapture(0) doesnt get access to the android camera.
The Code below shows how i edit the Video footage of the App at the moment. On PC it works perfect. But after building it, it shows no
video footage on android
Buidlozer Spec got permission btw..
capture = cv.VideoCapture(0)
class BinaryCam(Image):
def on_kv_post(self, base_widget):
#self.capture = cv.VideoCapture(0)
# cv.namedWindow("CV2 Image")
Clock.schedule_interval(self.update, 1.0 / 33.0)
def update(self, dt):
# display image from cam in opencv window
ret, frame = capture.read()
if ret==True:
# cv.imshow("CV2 Image", frame)
gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)
# convert it to texture
adaptive_thresh = cv.adaptiveThreshold(gray, 255, cv.ADAPTIVE_THRESH_MEAN_C, cv.THRESH_BINARY, 11, 3)
buf1 = cv.flip(adaptive_thresh, 0)
buf = buf1.tobytes()
texture1 = Texture.create(size=(adaptive_thresh.shape[1], adaptive_thresh.shape[0]),
colorfmt='luminance') # in grayscale gibts kein bgr
# if working on RASPBERRY PI, use colorfmt='rgba' here instead, but stick with "bgr" in blit_buffer.
texture1.blit_buffer(buf, colorfmt='luminance', bufferfmt='ubyte') # replacing texture
# display image from the texture
self.texture = texture1
Or maybe is there a way to get the Camera Frames from the Kivy Camera and edit them with OpenCV.
But i really would prefer this method i showed here with OpenCV.
Thank you

Related

Black video window after calibrate cameras with OpenCV

I am trying to calibrate two cameras. I'm using a code (not made by me) and it can generate the stereoMap without any problem. However, when I try to open the cameras with the new "settings" that are in the stereoMao file the windows where I should see the video calibrated are black. Sometimes one of the window shows a small part of the image that is being recorded by that camera.
This is the part of the code that is not working as I expected:
import numpy as np
import cv2
# Camera parameters to undistort and rectify images
cv_file = cv2.FileStorage()
cv_file.open('stereoMap.xml', cv2.FileStorage_READ)
stereoMapL_x = cv_file.getNode('stereoMapL_x').mat()
stereoMapL_y = cv_file.getNode('stereoMapL_y').mat()
stereoMapR_x = cv_file.getNode('stereoMapR_x').mat()
stereoMapR_y = cv_file.getNode('stereoMapR_y').mat()
cap_right = cv2.VideoCapture(0)
cap_left = cv2.VideoCapture(1)
while(cap_right.isOpened() and cap_left.isOpened()):
_, frame_right = cap_right.read()
_, frame_left = cap_left.read()
# Undistort and rectify images
frame_right = cv2.remap(frame_right, stereoMapR_x, stereoMapR_y, cv2.INTER_LANCZOS4, cv2.BORDER_CONSTANT, 0)
frame_left = cv2.remap(frame_left, stereoMapL_x, stereoMapL_y, cv2.INTER_LANCZOS4, cv2.BORDER_CONSTANT, 0)
cv2.imshow("frame right", frame_right)
cv2.imshow("frame left", frame_left)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap_right.release()
cap_left.release()
cv2.destroyAllWindows()
I have been using more than 5 images of a chessboard to calibrate the cameras and generate the stereoMap file.
Any idea to solve this problem?
Thanks,
Edit: These are the "black windows"

The video I recorded via webcam with opencv does not open

i tried to make a webcam video recording to a file using openCV python, i could not open the file with any of my video players. here is the code,
it works fine but I stop the recording and looking the file and it doesn't open. I guess there are some codec issues. I tried also (*'XVID') .avi format. but changed nothing.
here is the code
please help
from tkinter import *
from PIL import ImageTk, Image
import cv2
import threading
root = Tk()
root.geometry("750x500")
root.configure(bg="#0059aa")
#camera
camera_frame = LabelFrame(root, text=u"KAMERA STREAMING",
border=2,
width=398,
height=265)
camera_frame.place(x=183,y=33)
camera_label = Label(camera_frame,width=55,height=14)
camera_label.grid(row=0,column=0)
global capture
capture = cv2.VideoCapture(0)
# edit: close following two lines
# capture.set(3,250)
# capture.set(4,225)
global out
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
out = cv2.VideoWriter('blabla.mp4', fourcc, 20.0, (640, 480))
global stopCam
stopCam = False
def show_frames():
global capture
# read the capture
ret, frame = capture.read()
# turned into image and display
cv2image = cv2.cvtColor(frame,cv2.COLOR_BGR2RGB)
height, width, channels = cv2image.shape
img = Image.fromarray(cv2image)
imgtk = ImageTk.PhotoImage(image = img)
camera_label.imgtk = imgtk
camera_label.configure(image=imgtk,width=width,height=height)
# record
global out
out.write(frame)
# quit
if (stopCam):
out.release()
capture.release()
cv2.destroyAllWindows()
return
camera_label.after(20,show_frames)
p1 = threading.Thread(target=show_frames)
buttonLabel = Label(camera_frame)
buttonLabel.grid(row=1,column=0)
connectButton = Button (buttonLabel, text=u"connect", command=p1.start, width=14)
connectButton.grid(row=0,column=0)
stopButton = Button(buttonLabel, text=u"stop", command= lambda: globals().update(stopCam=True) , width=14)
stopButton.grid(row=0,column=1)
root.mainloop()
edit (also solved way):
I looked at some code that worked properly. and I saw capture.set() as the difference. When I close the capture.set() lines, I had no problems with either streaming or recording. Now the main problem is that I have to show the video in a label with a certain size. Without set() the video size gets too big. how can i solve it now?

Video playback using Tkinter and OpenCV too slow

If I use OpenCV to play video into its own window using this sort of logic:
cap = cv2.VideoCapture('video.mp4',cv2.CAP_FFMPEG)
while True:
ret, frame = cap.read()
if(ret):
cv2.imshow('', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
then it works well and smoothly. But if I use what appears to be the recommended way of playing into my own tkinter window, using the window.after() technique like this snippet:
def update(self):
# Get a frame from the video source
ret, frame = cap.read()
self.photo = PIL.ImageTk.PhotoImage(image = PIL.Image.fromarray(frame))
self.canvas.create_image(0, 0, image = self.photo, anchor = tk.NW)
self.update_id = self.window.after(self.VIDEO_READ_DELAY, self.update)
it is slow and stutters badly. I've played with the update delay without any real success, so I'm guessing that the processing overhead of the image conversion is what's causing the problem.
Can imshow() be made to play into my tkinter canvas directly?

Video Streaming from IP Camera in Python Using OpenCV cv2.VideoCapture

I am trying to get video stream in python from IP camera but i am getting an error. I am Using Pycharm IDE.
import cv2
scheme = '192.168.100.23'
host = scheme
cap = cv2.VideoCapture('http://admin:Ebmacs8485867#'+host+':81/web/admin.html')
while True:
ret, frame = cap.read()
# Place options to overlay on the video here.
# I'll go over that later.
cv2.imshow('Camera', frame)
k = cv2.waitKey(0) & 0xFF
if k == 27: # esc key ends process
cap.release()
break
cv2.destroyAllWindows()
Error:
"E:\Digital Image Processing\python\ReadingAndDisplayingImages\venv\Scripts\python.exe" "E:/Digital Image Processing/python/ReadingAndDisplayingImages/ReadandDisplay.py"
Traceback (most recent call last):
File "E:/Digital Image Processing/python/ReadingAndDisplayingImages/ReadandDisplay.py", line 14, in <module>
cv2.imshow('Camera', frame)
cv2.error: OpenCV(4.0.1) C:\projects\opencv-python\opencv\modules\highgui\src\window.cpp:352: error: (-215:Assertion failed) size.width>0 && size.height>0 in function 'cv::imshow'
warning: Error opening file (/build/opencv/modules/videoio/src/cap_ffmpeg_impl.hpp:901)
warning: http://admin:Ebmacs8485867#192.168.100.23:81/web/admin.html (/build/opencv/modules/videoio/src/cap_ffmpeg_impl.hpp:902)
You're most likely getting that error due to an invalid stream link. Insert your stream link into VLC player to confirm it is working. Here's a IP camera video streaming widget using OpenCV and cv2.VideoCapture.read(). This implementation uses threading for obtaining frames in a different thread since read() is a blocking operation. By putting this operation into a separate that that just focuses on obtaining frames, it improves performance by I/O latency reduction. I used my own IP camera RTSP stream link. Change stream_link to your own IP camera link.
Depending on your IP camera, your RTSP stream link will vary, here's an example of mine:
rtsp://username:password#192.168.1.49:554/cam/realmonitor?channel=1&subtype=0
rtsp://username:password#192.168.1.45/axis-media/media.amp
Code
from threading import Thread
import cv2
class VideoStreamWidget(object):
def __init__(self, src=0):
# Create a VideoCapture object
self.capture = cv2.VideoCapture(src)
# Start the thread to read frames from the video stream
self.thread = Thread(target=self.update, args=())
self.thread.daemon = True
self.thread.start()
def update(self):
# Read the next frame from the stream in a different thread
while True:
if self.capture.isOpened():
(self.status, self.frame) = self.capture.read()
def show_frame(self):
# Display frames in main program
if self.status:
self.frame = self.maintain_aspect_ratio_resize(self.frame, width=600)
cv2.imshow('IP Camera Video Streaming', self.frame)
# Press Q on keyboard to stop recording
key = cv2.waitKey(1)
if key == ord('q'):
self.capture.release()
cv2.destroyAllWindows()
exit(1)
# Resizes a image and maintains aspect ratio
def maintain_aspect_ratio_resize(self, image, width=None, height=None, inter=cv2.INTER_AREA):
# Grab the image size and initialize dimensions
dim = None
(h, w) = image.shape[:2]
# Return original image if no need to resize
if width is None and height is None:
return image
# We are resizing height if width is none
if width is None:
# Calculate the ratio of the height and construct the dimensions
r = height / float(h)
dim = (int(w * r), height)
# We are resizing width if height is none
else:
# Calculate the ratio of the 0idth and construct the dimensions
r = width / float(w)
dim = (width, int(h * r))
# Return the resized image
return cv2.resize(image, dim, interpolation=inter)
if __name__ == '__main__':
stream_link = 'your stream link!'
video_stream_widget = VideoStreamWidget(stream_link)
while True:
try:
video_stream_widget.show_frame()
except AttributeError:
pass
Related camera/IP/RTSP, FPS, video, threading, and multiprocessing posts
Python OpenCV streaming from camera - multithreading, timestamps
Video Streaming from IP Camera in Python Using OpenCV cv2.VideoCapture
How to capture multiple camera streams with OpenCV?
OpenCV real time streaming video capture is slow. How to drop frames or get synced with real time?
Storing RTSP stream as video file with OpenCV VideoWriter
OpenCV video saving
Python OpenCV multiprocessing cv2.VideoCapture mp4

stream from thermal camera (ip camera) on python , connection error

i want to stream from a thermal camera, usually it export its frames as gray scale frames
the thermal camera is an IP camera , i tried different codes and package but with no output.
when i change the code a little bit to view from a USB camera it works normally, so any help please.
this is the code i have tried :
import sys
sys.path.append('C:\Python27\Lib\site-packages')
import Tkinter as tk
import cv2
from PIL import Image, ImageTk
i=0
window = tk.Tk()
window.title('thermal image')
var = tk.IntVar()
width, height = 800, 600
cap = cv2.VideoCapture(0)
cap.open("http://169.254.110.119/")
left_label = tk.Label(window)
left_label.pack(side="left")
right_label = tk.Label(window)
right_label.pack(side="right")
def show_frame():
_, frame = cap.read()
print frame
if frame != None:
frame = cv2.flip(frame, 1)
img = Image.fromarray(frame)
imgtk = ImageTk.PhotoImage(image=img)
left_label.imgtk = imgtk
left_label.configure(image=imgtk)
left_label.after(10, show_frame)
show_frame()
window.mainloop()
I think that the image from the websitre is not being grabbed in the code, what worked for me was
img_requested = requests.get(url)
img_arr = np.array(bytearray(img_requested.content), dtype=np.uint8)
frame = cv2.imdecode(img_arr, -1)
And there you would get the frame (color picures/video).Keep in mind that you need to import requests and numpy as np.
It is important if you are using IP Webcam that you do not forget to write the '/shot.jpg'
at the end of the url, like this: 'http://190.160.0.0:8080/shot.jpg', so that it effectivelly grabs the image.

Categories

Resources