OpenCV imshow set color of pillarbox - python

I am using opencv in Python to play a video file full screen. The video is 4:3 aspect ratio, and imshow is by default maintaining the aspect ratio by creating a gray pillarbox along the right side of the screen.
I have not been succesfull in finding any documentation about how to manipulate this – i.e. how to change the color of the pillarbox / what I would presume is the default color of the empty window at the OS level? If changing the color is not explicitly supported by opencv is there a workaround? i.e. draw a black rectangle underneith the video frame?
#!/usr/bin/env python3
import cv2 as cv
cap = cv.VideoCapture("video.mp4")
while(cap.isOpened()):
ret,frame = cap.read()
frame = cv.resize(frame,(720,480))
cv.imshow("video", frame)
cv.namedWindow("video", cv.WND_PROP_FULLSCREEN)
cv.setWindowProperty("video", cv.WND_PROP_FULLSCREEN, cv.WINDOW_FULLSCREEN)
if cv.waitKey(10) & 0xFF == ord('q'):
break
cap.release()
cv.destroyAllWindows()

Related

Cropping a frame in video

What I'm trying to achieve is to crop my roi in the video frame into a variable and then further send it as a parameter..
Consider in face detection, and that x,y,x+w,y+h are the coordinates of the roi, which is the face and my aim is to crop that face and to show it.
The code below is just to explain my error and problem...
import cv2
cap=cv2.VideoCapture("D:\\Downloads\\video2.mp4")
#x,y,w,h, will change according the video i.e. where the face is detected.
#For the purpose of explaining, i took these values.
x=50
y=100
w=75
h=90
while(cap.isOpened()):
_,frame=cap.read()
crop_frame=frame[y:y+h,x:x+w]
cv2.imshow("Frame",frame)
cv2.imshow("crop_frame",frame)
cv2.destroyAllWindows()
cap.release()
But upon doing this, I get this error:
crop_frame=frame[y:y+h,x:x+w]
TypeError: 'NoneType' object is not subscriptable
This error wasn't there when i was working with images but on video inputs, i get this error.
Any solution to this problem or any alternative solution?
Basically you are slicing None when the video ends and no frame can be read: None[y:y+h,x:x+w]
You should use the retval to check if there is a frame to process, see the doc here: cv::VideoCapture::read.
So, try this code as experiment:
import cv2
cap=cv2.VideoCapture("video.mp4")
while(cap.isOpened()):
ret, frame=cap.read()
if ret:
cv2.imshow("Frame", frame)
else:
print('None frame:', frame)
break
cv2.destroyAllWindows()
cap.release()
There is no rendering because there is no time to do so, that's why you need to look at the next example.
Follows a simple script as example. These are the main points:
First, your loop is missing waytKey() function to allow the rendering, see the doc
here.
If you want your variable outside the loop, you must define
it outside the loop.
Also, you should choose which frame to crop.
You can also add HighGui (https://docs.opencv.org/4.1.0/d7/dfc/group__highgui.html) controls for selecting the frame, etc.
import cv2
cap=cv2.VideoCapture("video.mp4")
x=50
y=100
w=75
h=90
crop_frame = None
while(cap.isOpened()):
ret, frame = cap.read()
# if ret: to be added
cv2.imshow("Frame",frame)
keypressed = cv2.waitKey(10)
if keypressed == ord('q'):
break
if keypressed == ord('f'):
crop_frame = frame[y:y+h,x:x+w]
cv2.imshow("crop_frame", crop_frame)
cv2.destroyAllWindows()
cap.release()
cv2.imwrite('crop_frame.jpg', crop_frame)
You run and it shows the video.
Press 'F' and the current frame is cropped and presented in a new window.
Press 'Q': the loop exists and the cropped frame is saved as an image.

How to get rid of mouse cursor in OpenCV's display, as well as changing name of the window?

So I'm trying to display a video (named as test.mp4) with Python and OpenCV in full screen mode if possible and without showing OpenCV's cross cursor. Is there a way of doing this with some other library instead of OpenCV? Also I'm new to Stack Overflow so please say if I did something wrong.
I found out how to change name of window and size(full screen).
Even though I'm not satisfied with "fullscreen" because it has some white edges on the sides. If someone knows why is that happening help.
This is the code:
import cv2
import numpy as np
on = "on"
file_name = "test.mp4"
window_name = "randomsheetblin"
interframe_wait_ms = 30
cap = cv2.VideoCapture(file_name)
if not cap.isOpened():
print("Error: Could not open video.")
exit()
cv2.namedWindow(window_name, cv2.WND_PROP_FULLSCREEN)
cv2.setWindowProperty(window_name, cv2.WND_PROP_FULLSCREEN, cv2.WINDOW_FULLSCREEN)
while on == "on":
ret, frame = cap.read()
if not ret:
#print("Reached end of video, exiting.")
break
cv2.imshow(window_name, frame)
if cv2.waitKey(interframe_wait_ms) & 0x7F == ord('p'):
#print("Exit requested.")
break
cap.release()
cv2.destroyAllWindows()
Result should be a fullscreen window with custom name, without OpenCV's cross cursor, even windows default cursor should be alright.

Python OpenCV images get blurry after successive shots

I'm new to Open CV and python, and I've been facing a problem:
I've been doing a project on my Raspberry Pi where the webcam takes a grey scale image, removes the background, and saves it in a folder.
This is used by a machine learning algorithm to detect the object in the image.
The webcam is fixed at a particular point so I first take an image of the background and then take a picture of the object. The background is then removed from the object and it looks fine.
But if I repeat the process and overwrite the image, it becomes blurred.
This effect keeps happening until after about three or four shots the image becomes blurry and my program cant identify the object in it.
My code is:
#get Background
import cv2
cam = cv2.videoCapture(0)
ret, frame = cam.read()
if ret:
img_name = '/home/pi/Desktop/background.png'
grey_img = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
cv2.imwrite(img_name, grey_img)
print('{} written'.format(img_name))
cam.release()
#takeImage
import cv2
import numpy as np
ret, frame = cam.read()
back = cv2.imread('/home/pi/Desktop/background.png')
if ret:
img_name = '/home/pi/Desktop/img_capture.png'
grey_img = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
cv2.imwrite(img_name, grey_img)
grey_obj = cv2.subtract(cv2.imread(img_name), back)
cv2.imwrite(img_name, grey_obj)
print('{} written'.format(img_name))
cam.release()
I'm using a Logitech webcam but I'm not sure of the exact model
Please help me out, and thanks in advance.
Clear at the start:
Not so much:
Not at all:

Corrupt JPEG Data: 1273 extraneous bytes before marker. Opencv 3/python2.7

This is the code when i execute it:
You can see the frame opens but doesnt show anything
I want to use a usb camera with a raspberry pi 3 model b v1.2 using opencv 3.3 and python 2.7.
I work with opencv in an virtual enviroment.
import numpy as np
import cv2
cap = cv2.VideoCapture(0)
while(True):
ret, frame = cap.read() #Capture frame-by-frame
#Our operations on the frame come here
#gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
#Display resulting frame
cv2.imshow('frame',frame)
cv2.waitKey(10)
#if cv2.waitKey(1) & 0xFF == ord('q'):
# break
#when everything done, release the capture
cap.release()
cv2.destroyAllWindows()
I just have no idea how to get around this error. I already searched the error and i am getting helpless, anyone having an idea?
EDIT: i am currently playing around with the code and i can get frames but most of the time the screen stays grey. I use # to show how the code looks now
Ok, it now opens a window and shows the output of the camera
Because of this code:
import sys
sys.path.append('/home/pi/.virtualenvs/cv/lib/python2.7/site-
packages/usr/local/lib/python2.7/site-packages')
and i also use sudo python program.py in the terminal
But this Error :"NameError: name 'CV_CAP_PROP_FRAME_HEIGHT' is not defined" still persists...

opencv, python: How to track live trackers from environment and find changes in environment

I'm trying my hands on OpenCV with Python and 'am kind of stuck.
I want to find specific trackers from every frame of a live camera and detect changes in the environment with a tracker of different color (say red).
Right now, my code takes a frame of my video which I select, and shows trackers which are too much to understand.
Can you help me in fixing this code?
import numpy as np
import cv2
from matplotlib import pyplot as plt
cap = cv2.VideoCapture(0)
while(True):
# Capture frame-by-frame
ret, frame = cap.read()
# Our operations on the frame come here
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# Display the resulting frame
cv2.imshow('frame',gray)
# Initiate feature detector
orb = cv2.FastFeatureDetector_create()
# find the keypoints with ORB
kp = orb.detect(gray)
img2 = cv2.drawKeypoints(frame, kp, outImage=None, color=(0, 255, 0), flags=0)
plt.imshow(img2), plt.show()
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()
This is my image without an object (bottle)
This is me with an object
Now what I want to track changes in between the images (with bottle and without bottle), i.e changes in environment of an image should be tracked live on videocam!

Categories

Resources