OpenCV putText does not work after flipping the image - python

I'd like to grab images from the camera and flip them left/right so that the view performs like a mirror. However, I also like to add some text to the view, but it turns out that after flipping the image using np.fliplr(frame), cv.putText does no longer work.
Here is my minimal example using python 3.5.2:
import numpy as np
import cv2
import platform
if __name__ == "__main__":
print("python version:", platform.python_version())
cap = cv2.VideoCapture(0)
while(True):
# Capture frame-by-frame
ret, frame = cap.read()
cv2.putText(frame,'Hello World : Before flip',(100, 100), cv2.FONT_HERSHEY_SIMPLEX, 1,(255,255,255),2,cv2.LINE_AA)
frame = np.fliplr(frame)
cv2.putText(frame,'Hello World : After flip',(100, 200), cv2.FONT_HERSHEY_SIMPLEX, 1,(255,255,255),2,cv2.LINE_AA)
# Process the keys
key = cv2.waitKey(1) & 0xFF
if key == ord('q'):
print("quit")
break
# show the images
cv2.imshow('frame',frame)
cap.release()
cv2.destroyAllWindows()
Resulting frame w/ flip:
Resulting frame w/o flip:

I suspect it's due to cv2.putText is not compatible with np.array which is the return value of np.fliplr(frame). I suggest that you use frame = cv2.flip(frame, 1) instead.
import numpy as np
import cv2
import platform
if __name__ == "__main__":
print("python version:", platform.python_version())
cap = cv2.VideoCapture(0)
while(True):
# Capture frame-by-frame
ret, frame = cap.read()
cv2.putText(frame,'Hello World : Before flip',(100, 100), cv2.FONT_HERSHEY_SIMPLEX, 1,(255,255,255),2,cv2.LINE_AA)
frame = cv2.flip(frame, 1)
cv2.putText(frame,'Hello World : After flip',(100, 200), cv2.FONT_HERSHEY_SIMPLEX, 1,(255,255,255),2,cv2.LINE_AA)
# Process the keys
key = cv2.waitKey(1) & 0xFF
if key == ord('q'):
print("quit")
break
# show the images
cv2.imshow('frame',frame)
cap.release()
cv2.destroyAllWindows()

Just flip the frame before putting the text:
frame = cv2.flip(frame, 1)
cv2.putText(...)

Related

Why does my image taken with OpenCV appear smaller than that of libcamera?

I am currently working on a project which makes use of a Raspberry Pi and its Camera Module v2.1.
I need to scan some barcodes with the camera of which I am using the OpenCV and pyzbar libraries.
I am running into some trouble with the image that OpenCV is returning, example below:
Image returned from running libcamera-hello:
Image returned from running my script:
As you can see the images are very different, the OpenCV image is more zoomed in.
I've tried resizing the image and even changing the size of the frame but it doesn't seem to help, the image just gets stretched!
Does anyone have any ideas on why this might be happening?
My script for capturing the images is below:
import cv2
from pyzbar import pyzbar
from gpiozero import Button
from readBarcodeData import read_text
button = Button(25)
def read_barcodes(frame):
barcodes = pyzbar.decode(frame)
for barcode in barcodes:
x, y , w, h = barcode.rect
barcode_info = barcode.data.decode('utf-8')
cv2.rectangle(frame, (x, y),(x+w, y+h), (0, 255, 0), 2)
with open("barcode_result.txt", mode ='w') as file:
file.write(str(barcode_info).replace("'", ""))
return frame
def main():
while True:
if button.is_pressed:
camera = cv2.VideoCapture(0)
ret, frame = camera.read()
while ret:
ret, frame = camera.read()
frame = read_barcodes(frame)
cv2.imshow('Barcode Scanner', frame)
if cv2.waitKey(0) & 0xFF == 27:
break
break
camera.release()
cv2.destroyAllWindows()
read_text()
if __name__ == '__main__':
main()
EDIT:
I have also tried capturing an image using the following code:
import cv2
vid = cv2.VideoCapture(0)
while(True):
# Capture the video frame
ret, frame = vid.read()
# Display the resulting frame
cv2.imshow('frame', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# After the loop release the cap object
vid.release()
# Destroy all the windows
cv2.destroyAllWindows()
But I still get a cropped image.
EDIT 2:
Returned properties from the video capture:
CV_CAP_PROP_FRAME_WIDTH: '640.0'
CV_CAP_PROP_FRAME_HEIGHT : '480.0'
[ WARN:0] global /tmp/pip-wheel-j62hpwu1/opencv-python_19cf39855c924932a2df50dd2b502cd2/opencv/modules/videoio/src/cap_v4l.cpp (1911) getProperty VIDEOIO(V4L2:/dev/video0): Unable to get camera FPS
CAP_PROP_FPS : '-1.0'
CAP_PROP_POS_MSEC : '911170.05'
CAP_PROP_FRAME_COUNT : '-1.0'
CAP_PROP_BRIGHTNESS : '-1.0'
CAP_PROP_CONTRAST : '-1.0'
CAP_PROP_SATURATION : '-1.0'
CAP_PROP_HUE : '-1.0'
CAP_PROP_GAIN : '-1.0'
CAP_PROP_CONVERT_RGB : '1.0'
I managed to "fix" this by using the PiCamera library to capture the image and then run it through cv2:
Code for reading in PiCamera image is below:
import cv2
from time import sleep
from pyzbar import pyzbar
from gpiozero import Button
from picamera.array import PiRGBArray
import picamera
from readBarcodeData import read_text
button = Button(25)
def read_barcodes(frame):
barcodes = pyzbar.decode(frame)
for barcode in barcodes:
x, y , w, h = barcode.rect
barcode_info = barcode.data.decode('utf-8')
cv2.rectangle(frame, (x, y),(x+w, y+h), (0, 255, 0), 2)
with open("barcode_result.txt", mode ='w') as file:
file.write(str(barcode_info).replace("'", ""))
return frame
def main():
while True:
if button.is_pressed:
with picamera.PiCamera() as camera:
rawCapture = PiRGBArray(camera)
#camera.resolution = (3280, 2464)
camera.start_preview()
#sleep(1)
camera.capture(rawCapture, format="bgr")
img = rawCapture.array
#camera = cv2.VideoCapture(0)
#ret, frame = camera.read()
ret = True
while ret:
#ret, frame = img
frame = read_barcodes(img)
#cv2.imshow('Barcode Scanner', frame)
#print(frame.shape)
#if cv2.waitKey(0) & 0xFF == 27:
#break
break
cv2.destroyAllWindows()
read_text()
if __name__ == '__main__':
main()
The image captured by PiCamera seems to return the full image with no cropping so works a treat.

Facecam Video does not open with cv2.VideoCapture() and cannot be read

I'm new to OpenCV and just started learning
I am using macOS, python version 3.8.1
My code:
import cv2
# takes facecam video
cap = cv2.VideoCapture(-1)
while True:
# Capture frame-by-frame
ret, frame = cap.read()
if cap.isOpened() == True:
# Our operations on the frame come here
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# Display the resulting frame
cv2.imshow('frame',gray)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
else:
cap.open(-1)
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()
This works for me
import cv2
cap = cv2.VideoCapture(0)
while True:
ne, frame = cap.read()
cv2.imshow("Webcam Capture", frame)
if cv2.waitKey(1) & 0xFF == ord("A"):
break
cap.release()
cv2.destroyAllWindows()

Does anyone know how to code for getting a frame using your webcam?

I'm trying to get a frame from my webcam but I don't know where the frame is located.
this is my code:
import cv2
import numpy as np
cap = cv2.VideoCapture(0)
while True:
_, frame = cap.read()
if frame is None:
break
cv2.imshow('app', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
In the code that you posted, the frame is the image that is captured from the webcam at that point in time.
import cv2
import numpy as np
cap = cv2.VideoCapture(0)
while True:
_, frame = cap.read()
if frame is None:
break
cv2.imshow('app', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cv2.waitKey(0)
cap.release()
cv2.destroyAllWindows()
In your program indentation problem in if condition
If you press "q" then the frame is captured, and the frame stored in "frame" variable

imshow create new windows with opencv on ubuntu

I tried to show images from camera using cv2.imshow, but instead of updating it creates new windows.
This is the code
import cv2
if __name__ == '__main__':
roi_width = 300
roi_height = 300
cam = cv2.VideoCapture(0)
while True:
ret, original = cam.read()
roi = original[0:roi_height, 0:roi_width]
cv2.rectangle(original, (0, 0), (roi_width+5, roi_height+5), 5)
cv2.imshow("original", original)
cv2.imshow("roi", roi)
k = cv2.waitKey(1)
if k == ord('q'):
break
cv2.destroyAllWindows()
This is the result I got after 10 iterations

Cannot Close Video Window in OpenCV

I would like to play a video in openCV using python and close that window at any time, but it is not working.
import numpy as np
import cv2
fileName='test.mp4' # change the file name if needed
cap = cv2.VideoCapture(fileName) # load the video
while(cap.isOpened()):
# play the video by reading frame by frame
ret, frame = cap.read()
if ret==True:
# optional: do some image processing here
cv2.imshow('frame',frame) # show the video
if cv2.waitKey(1) & 0xFF == ord('q'):
break
else:
break
cv2.waitKey(1)
cv2.destroyAllWindows()
cv2.waitKey(1)
The window opens and starts playing the video, but I cannot close the window.
You can use cv2.getWindowProperty('window-name', index) to detect if the window is closed. I'm not totally sure about the index but this worked for me:
import cv2
filename = 'test.mp4'
cam = cv2.VideoCapture(filename)
while True:
ret, frame = cam.read()
if not ret:
break
cv2.imshow('asd', frame)
cv2.waitKey(1)
if cv2.getWindowProperty('asd', 4) < 1:
break

Categories