I'm trying to read license plate. So I found this tutorial : https://medium.com/programming-fever/license-plate-recognition-using-opencv-python-7611f85cdd6c
And when I run it the cv2.imshow() isn't working every time. Sometime I got the image but sometime just the window with a tiny black rectangle in it. Here is the little window
img = cv2.imread('2.jpg',cv2.IMREAD_COLOR)
img = cv2.resize(img, (640,480) )
cv2.imshow('actual', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
Just this tiny code is supposed to work everytime if the image exists. But it doesn't.
Does anyone have any clue about this ?
Thanks
Well to make it work I changed two things :
First I had cv2.namedWindow('actual', cv2.WINDOW_NORMAL)
And then I updated using : pip3 install opencv
And now it's working every time.
Try to put the destroyAllWindows in a loop to close it properly (pressing q):
img = cv2.imread('2.jpg',cv2.IMREAD_COLOR)
img = cv2.resize(img, (640,480) )
cv2.imshow('actual', img)
while True:
if cv2.waitKey(1) & 0xFF == ord('q'):
cv2.destroyAllWindows()
break
Related
I'm using the OpenCV webcam example. Works great, but wondering, if it's possible to add a "camera reconnect function". When I unplug the camera, the code will crash. That's normal, but I would like to keep it running until I replug the camera again.
I tried "try: & except:" as you can see below. Now the python doesn't crash & when I unplug the camera, it will start printing "disconnected" to the console. However, when I reconnect the camera back, it would not start automatically, need to reset the program.
Thanks
import numpy as np
import cv2
cap = cv2.VideoCapture(2)
#cap = cv2.VideoCapture(1)
if cap.isOpened():
while(True):
try:
# Capture frame-by-frame
ret, im= cap.read()
# Display the resulting frame
cv2.imshow('frame', im)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
except:
print('Disconnected')
else:
print("camera open failed")
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()
I'm currently in the works of making an auto-aiming turret, and my camera's have a noticeable fish eye effect, which is totally fine. I'm using OpenCV's undistort() function to handle this, with data from a camera checkerboard calibration.
I will most likely be running the vision system on a raspberry pi 4, and currently, my undistort function takes 80-90% of my CPU (i5-8600k OC 5GHz) when processing both of my cameras at 1280x720px, ideally this px as it's the largest and will provide best accuracy. Also note I'm aiming for a 15Hz update time.
Any ideas on how to make this more lightweight? Here's my code that I'm currently running as a test:
from cv2 import cv2
import numpy as np
import yaml
import time
cam1 = cv2.VideoCapture(0)
cam2 = cv2.VideoCapture(1)
cam1.set(3, 1280)
cam1.set(4, 720)
cam2.set(3, 1280)
cam2.set(4, 720)
#load calibration matrix
with open ("calibration_matrix.yaml") as file:
documents = yaml.full_load(file)
x=0
for item, doc in documents.items():
if x == 0:
mtx = np.matrix(doc)
x = 1
else:
dist = np.matrix(doc)
def camera(ID, asd):
if asd == -1:
ID.release()
ret, frame = ID.read()
if ret:
newcameramtx, roi = cv2.getOptimalNewCameraMatrix(mtx,dist,(w,h),1,(w,h))
undistortedFrame = cv2.undistort(frame, mtx, dist, None, newcameramtx)
undistortedFrame = undistortedFrame[y:y+h, x:x+w]
return undistortedFrame
while True:
frame1 = camera(cam1, 0)
frame2 = camera(cam2, 0)
cv2.imshow('Frame 1', frame1)
cv2.imshow('Frame 2', frame2)
if cv2.waitKey(1) & 0xFF == ord('q'):
camera(cam1, -1)
camera(cam2, -1)
cv2.destroyAllWindows()
Comments above resolved, here's the solution:
As #Micka said,
use initundistortrectifymap() (once) and remap() (for each image)
initundistortrectifymap() basically takes the heavy load off of the undistort function (Micka) In practice, you run initundistortrectifymap() at the start of the program with the image calibration matrix and distance coefficients, and then initundistortrectifymap() returns two maps, map1 and map2.
These maps can be passed into the remap() function to remap your image, which is a significantly lighter function than undistort(). In my particular case, I have a fisheye camera, and OpenCV has fisheye modules that are optimized to undistort fish eye cameras with ease.
I am trying to capture image in every 5 seconds using opencv through my laptop's built-in webcam. I am using time.sleep(5) for the required pause. In every run, the first image seems to be correctly saved but after that rest all the images are being saved as an unsupported format (when i am opening them). Also I am unable to break the loop by pressing 'q'.
Below is my code.
import numpy as np
import cv2
import time
cap = cv2.VideoCapture(0)
framerate = cap.get(5)
x=1
while(True):
# Capture frame-by-frame
ret, frame = cap.read()
cap.release()
# Our operations on the frame come here
filename = 'C:/Users/shjohari/Desktop/Retail_AI/MySection/to_predict/image' + str(int(x)) + ".png"
x=x+1
cv2.imwrite(filename, frame)
time.sleep(5)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()
Any help is appreciated.
Just a small change, solved my issue.
I included the below code inside the loop :P
cap = cv2.VideoCapture(0)
framerate = cap.get(5)
Background - I have python and required scripts installed on my desktop.
I am developing a face recognition WebApp.
It is working fine from Command Line but when I try to run it from localhost on wampserver, the webcam lights get on but no webcam window appears and the page starts loading for unlimited time.
Here is the code for data training
#!C:\Users\Gurminders\AppData\Local\Programs\Python\Python35-32\python.exe
import cv2
import os
def assure_path_exists(path):
dir = os.path.dirname(path)
if not os.path.exists(dir):
os.makedirs(dir)
# Start capturing video
vid_cam = cv2.VideoCapture(0)
# Detect object in video stream using Haarcascade Frontal Face
face_detector = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
# For each person, one face id
face_id = input('Please Enter Casual ID --> ')
# Initialize sample face image
count = 0
assure_path_exists("dataset/")
# Start looping
while(True):
# Capture video frame
_, image_frame = vid_cam.read()
# Convert frame to grayscale
gray = cv2.cvtColor(image_frame, cv2.COLOR_BGR2GRAY)
# Detect frames of different sizes, list of faces rectangles
faces = face_detector.detectMultiScale(gray, 1.3, 5)
# Loops for each faces
for (x,y,w,h) in faces:
# Crop the image frame into rectangle
cv2.rectangle(image_frame, (x,y), (x+w,y+h), (255,0,0), 2)
# Increment sample face image
count += 1
# Save the captured image into the datasets folder
cv2.imwrite("dataset/User." + str(face_id) + '.' + str(count) + ".jpg", gray[y:y+h,x:x+w])
# Display the video frame, with bounded rectangle on the person's face
cv2.imshow('frame', image_frame)
# To stop taking video, press 'q' for at least 100ms
if cv2.waitKey(100) & 0xFF == ord('q'):
break
# If image taken reach 100, stop taking video
elif count>100:
break
# Stop video
vid_cam.release()
# Close all started windows
cv2.destroyAllWindows()
It works fine on command line but not from localhost on wampserver.
I solved this problem
I replaced
if cv2.waitKey(100) & 0xFF == ord('q'):
With
if cv2.waitKey(5000):
here 5000 are 5 seconds
I come from RDBMS background and just starting on python. below is a simple code i written to invoke my web cam via python
import cv2
vid = cv2.VideoCapture(0)
while vid == True:
print("Connected....");
if cv2.waitKey(0) : break
cv2.release();
but i am getting error
AttributeError: module 'cv2.cv2' has no attribute 'release'
while executing it. I am running this code using python3.5 and on linux 14.04 platform. I can see cv2 package installed via help("modules") list and it gets imported as well without error . however i dont see it in the interpreter list of pycharm. please help.
cv2.release() does not exist. I think what you are trying to do is vid.release()
cv2 is the opencv module and vid is the VideoCapture object. which is the one that you have to do the release.
UPDATE:
The code you have has several mistakes. Before I only addressed the one you asked, but lets go through all of them.
First one, the indentation is wrong, I guess maybe it is from copying the code.
Second one
while vid == True:
This is not the correct way to do it. You can use the vid.isOpened() function to see if it opened/connected to the webcam.
Third one, you do not need to use ; after the instructions.
Fourth one, this one is not an error, but something that is not necessary
if cv2.waitKey(0) : break
the if is not necessary, waitKey will return the key pressed as an ascii character, if you use a number other than 0 it will return 0 if no key was pressed. But with 0 it will wait for a key to be pressed "blocking" the current thread (in case you have more than one). However, it will not wait unless that you have a imshow window opened.
Now, the complete code with those changes that I wrote and that checks if the script can connect to a camera will be
import cv2
vid = cv2.VideoCapture(0)
if vid.isOpened():
print ("Connected....")
else:
print ("Not Connected....")
vid.release()
In a similar fashion you can display the video until a key is pressed:
import cv2
vid = cv2.VideoCapture(0)
if vid.isOpened():
print ("Connected....")
while True:
ret, frame = vid.read()
if ret:
cv2.imshow("image", frame)
else:
print ("Error aqcuiring the frame")
break
if cv2.waitKey(10) & 0xFF:
break
else:
print ("Not Connected....")
vid.release()
cv2.destroyAllWindows()
If something is not clear, feel free to ask :)
import cv2
import numpy
img = cv2.imread("lena.jpg", 1)
cv2.imshow("image", img)
cv2.waitKeyEx(0)
cv2.destroyAllWindows()