File on Google Drive doesn't appear in Colab - python

I'm learning to use OpenCV on Colab to deal with object tracking in videos.
I have a sample .mp4 video called low den.mp4 that I uploaded "indirectly" to my own gdrive. So that I can mount it by:
import cv2
from google.colab import drive
drive.mount('/content/gdrive')
then I can run the cell successfully by
path = "/gdrive/My Drive/low den.mp4"
But when I call
video = cv2.VideoCapture(path)
if not video.isOpened():
print('Error while loading the video!')
sys.exit()
Colab tells me this:
Error while loading the video!
An exception has occurred, use %tb to see the full traceback.
SystemExit
I tried the "direct" method mentioned elsewhere:
from google.colab import files
uploaded = files.upload()
Video upload alright. Then if I call
video = cv2.VideoCapture(uploaded)
if not video.isOpened():
print('Error while loading the video!')
sys.exit()
Colab tells me this:
error Traceback (most recent call
last)
<ipython-input-39-b5c3939fe4ac> in <module>
----> 1 video = cv2.VideoCapture(uploaded)
2 if not video.isOpened():
3 print('Error while loading the video!')
4 sys.exit()
error: OpenCV(4.6.0) :-1: error: (-5:Bad argument) in function
'VideoCapture'
> Overload resolution failed:
> - Can't convert object to 'str' for 'filename'
> - VideoCapture() missing required argument 'apiPreference' (pos 2)
> - Argument 'index' is required to be an integer
> - VideoCapture() missing required argument 'apiPreference' (pos 2)
I need some help on understanding what went wrong in the "indirect" vs "direct" methods. And for the "direct" dialogue upload, how do I convert the uploaded video object to a file path and use it for other cv functions?
Thank you

Related

OpenCV CL_OUT_OF_RESOURCES when running code that worked before

I am running OpenCV to stitch some images together and before today was working fine, but after trying to run similar code today I am getting error messages.
Code is:
import cv2
import os
images =[]
path = "Folder"
for image in os.listdir(path):
img = cv2.imread(os.path.join(path,image))
images.append(img)
print("There are {} images".format(len(images)))
print("Images are read")
print("Creating stitcher")
stitcher = cv2.Stitcher.create(mode=1)
print("Stitcher is running")
(status, stitched) = stitcher.stitch(images)
cv2.imwrite("File.png", stitched)
And the errors I am getting are:
cv2.error: OpenCV(4.6.0)
D:\a\opencv-python\opencv-python\opencv\modules\core\src\ocl.cpp:5954:
error: (-220:Unknown error code -220) OpenCL error CL_OUT_OF_RESOURCES
(-5) during call: clEnqueueReadBuffer(q, handle=000001C39C840AE0,
CL_TRUE, 0, sz=1583382528, data=000001C4E6132080, 0, 0, 0) in function
'cv::ocl::OpenCLAllocator::map' OpenCV(4.6.0) Error: Unknown error
code -220 (OpenCL error CL_INVALID_COMMAND_QUEUE (-36) during call:
clEnqueueMapBuffer(handle=000001C3FB376060, sz=3341583) =>
0000000000000000) in cv::ocl::OpenCLAllocator::deallocate_, file
D:\a\opencv-python\opencv-python\opencv\modules\core\src\ocl.cpp, line
5761
I have tried to search up some results but I couldn't find a similar scenario
I have had the same code but with a different path running and it has been reading a lot more images and it does not throw any errors (147MB folder vs a 70MB folder which throws the error), am I missing a way to purge my memory or something?

Get Image Object size in Python in Bytes - BadRequest Error in Azure

I have an image object that I've accepted via a streamlit interface. Here's its type: <class 'streamlit.uploaded_file_manager.UploadedFile'>
I need to get the size of this image in bytes or megabytes. The image is not stored on my device.
I tried using
def img_resize(image):
img2 = Image.open(image)
img_file = io.BytesIO()
img2.save(img_file, 'png')
image_file_size = img_file.tell()
print(image_file_size)
img2.close()
# This function connects to azure services and generates the resources and generates the results
def azure_result(image_name, image):
img_resize(image)
Output:
14386671
2021-08-12 12:57:01.892 Traceback (most recent call last):
File "path", line 1709, in read_in_stream
raise models.ComputerVisionOcrErrorException(self._deserialize, response)
azure.cognitiveservices.vision.computervision.models._models_py3.ComputerVisionOcrErrorException: Operation returned an invalid status code 'Bad Request'
The file size printed is 14386671, the image size as per the system is 3.77 mb. When i further pass the image object to the Azure Cognitive Service, I get a bad request error.
How do I solve this?
We can get the size of an object by storing them in a variable and printing it as below:
print(sys.getsizeof(content))
Or we can add an extension to img_file as “. size”, this will get the actual size in bytes.
If we would like to get the file size in KB, MB and GB and convert them to bytes we can follow below conversion table:
We can add these extensions in img_resize(image) functions, we’ll be able to capture the correct bytes.
Prerequisites before you connect to Azure Cognito Service is to install the pip lib as below in terminal:
pip install azure-cognitiveservices-vision-computervision
Later below code gives us insight on how to connect to Azure Cognito Service:
from azure.cognitiveservices.vision.computervision import ComputerVisionClient
from azure.cognitiveservices.vision.computervision.models import VisualFeatureTypes
from msrest.authentication import CognitiveServicesCredentials
import os
region = os.environ['ACCOUNT_REGION']
key = os.environ['ACCOUNT_KEY']
credentials = CognitiveServicesCredentials(key)
client = ComputerVisionClient(
endpoint="https://" + region + ".api.cognitive.microsoft.com/",
credentials=credentials
)
Can get more information from the Python documentation for Azure.

AttributeError: 'Image' object has no attribute 'frame'

I am trying to save images from Carla in my disk, but I receive this error on the terminal.
Traceback (most recent call last):
File "carla_basic_tutorial.py", line 83, in <lambda>
'out%02d/%06d.png' % (n_output, image.frame)
AttributeError: 'Image' object has no attribute 'frame'
I have already installed the libraries from requirements files and Pillow too, the drivers of GPU were installed.
The part of code is available below
# Spawn the camera and attach it to the vehicle
camera = world.spawn_actor(
camera_bp,
camera_transform,
attach_to=vehicle
)
actor_list.append(camera)
print('created %s' % camera.type_id)
# Check how much "out" folders already exists
n_output = len([d for d in os.listdir() if d.startswith('out')])
# Sets the function that will be called by the camera
# This will save the images to disk at a "out" folder
camera.listen(lambda image: image.save_to_disk(
'out%02d/%06d.png' % (n_output, image.frame)
))
The full code is available here Full code
I solved this using the attribute image.frame_number
camera.listen(lambda image: image.save_to_disk(
'out%02d/%06d' % (n_output, image.frame_number)
))

When I am trying to get live stream from youtube using opencv and camgear I am getting the following error

I want to get the live stream from youtube, and for that, I have used opencv along with the package vidgear. But while running the code, I am getting the following error. I am sure that there is no problem with the URL.
I have tried with pafy and streamlink. Even though both have given the result but after few frames, it was getting stuck and I want sequential frames without any pause.
import cv2
from vidgear.gears import CamGear
stream = CamGear(source="https://www.youtube.com/watch?v=VIk_6OuYkSo", y_tube =True, time_delay=1, logging=True).start() # YouTube Video URL as input
while True:
frame = stream.read()
if frame is None:
break
cv2.imshow("Output Frame", frame)
key = cv2.waitKey(30)
if key == ord("q"):
break
cv2.destroyAllWindows()
stream.stop()
Error output ::
'NoneType' object has no attribute 'extension'
Traceback (most recent call last):
File "C:\Users\CamfyVision\AppData\Local\Programs\Python\Python36\lib\site-packages\vidgear\gears\camgear.py", line 120, in __init__
print('Extension: {}'.format(_source.extension))
AttributeError: 'NoneType' object has no attribute 'extension'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "DronrStream.py", line 4, in <module>
stream = CamGear(source="https://www.youtube.com/watch?v=VIk_6OuYkSo", y_tube =True, time_delay=1, logging=True).start() # YouTube Video URL as input
File "C:\Users\CamfyVision\AppData\Local\Programs\Python\Python36\lib\site-packages\vidgear\gears\camgear.py", line 125, in __init__
raise ValueError('YouTube Mode is enabled and the input YouTube Url is invalid!')
ValueError: YouTube Mode is enabled and the input YouTube Url is invalid!
#Adithya Raj I'm the author of VidGear Video Processing python library.
This error is because of a bug with YouTube live streams and is already been resolved in this commit. Kindly update vidgear as follows:
pip install -U vidgear
i was try to run your script and i got error in URL link but when i replace with other URL link then you're script works fine no error. have look pics

os.mknod returns [error38] function not implemented in google colab

I am trying to run the following piece of code on google colab.
dir_path = '/content/drive/My Drive/Colab Notebooks'
log_loss_path =os.path.join(dir_path, 'log_loss.txt')
if not os.path.isfile(log_loss_path):
os.mknod(log_loss_path)
but i get the error [Errno 38] Function not implemented
OSError Traceback (most recent call last)
<ipython-input-15-bd3880e6bb8b> in <module>()
2 log_loss_path = os.path.join(dir_path, 'log_loss.txt')
3 if not os.path.isfile(log_loss_path):
----> 4 os.mknod(log_loss_path)
OSError: [Errno 38] Function not implemented
can anyone help to solve it?
/content/drive is a FUSE filesystem which doesn't support this operation.
If you are just trying to create a file, use instead open(log_loss_path, 'w').

Categories

Resources