AttributeError: 'dict' python opencv and openalpr - python

Just having a play around with drawing on webcam stream with opencv and and openalpr, I have both of them working on their own but when I add them together i get this error.
Invalid pattern provided: auwide
Valid patterns are located in the auwide.patterns file
Plate #1
Plate Confidence
- 6U01 82.790466
Traceback (most recent call last):
File "C:/Users/Alex/PycharmProjects/displayrec/testing.py", line 31, in
<module>
rec = plate.detectMultiScale(frame, 1.3, 5)
AttributeError: 'dict' object has no attribute 'detectMultiScale'
Process finished with exit code 1
I have had a read on here Python OpenCV face detection code sometimes raises `'tuple' object has no attribute 'shape'`
I tried adding it to my code but still get the same error.
it's weird because it works for a second and throws a partial plate but then crashes with that error above.
import numpy as np
import cv2
import sys
import os
from openalpr import Alpr
alpr = Alpr("auwide", "openalpr.conf", "runtime_data")
if not alpr.is_loaded():
print("Error loading OpenALPR")
sys.exit(1)
alpr.set_top_n(1)
alpr.set_default_region("auwide")
plate = cv2.CascadeClassifier('au.xml')
vc = cv2.VideoCapture(0)
while True:
ret, frame = vc.read()
img_gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
noise_removal = cv2.bilateralFilter(img_gray, 9, 75, 75)
equal_histogram = cv2.equalizeHist(noise_removal)
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5))
morph_image = cv2.morphologyEx(equal_histogram, cv2.MORPH_OPEN, kernel,
iterations=15)
sub_morp_image = cv2.subtract(equal_histogram,morph_image)
rec = plate.detectMultiScale(frame, 1.3, 5)
for (x, y, w, h) in rec:
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 0, 255), 2)
roi_gray = frame[y:y + h, x:x + w]
roi_color = frame[y:y + h, x:x + w]
cv2.imshow("Result",frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
if ret:
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cv2.imwrite("img.jpg", sub_morp_image)
results = alpr.recognize_file("img.jpg")
i = 0
for plate in results['results']:
i += 1
print("Plate #%d" % i)
print(" %12s %12s" % ("Plate", "Confidence"))
for candidate in plate['candidates']:
prefix = "-"
if candidate['matches_template']:
prefix = "*"
print(" %s %12s%12f" % (prefix, candidate['plate'],
candidate['confidence']))
else:
break;
vc.release()
alpr.unload()
cv2.destroyAllWindows()

Related

Why do I get the following error after and hour of operation cv2.error:(-215:Assertion failed) !src.empty() in function 'cvtColor'

Things work fine for 30 minutes to an hour, then I get the following error:
active
inactive
active
active
active
inactive
active
Traceback (most recent call last):
File "interface/larry5.py", line 93, in <module>
vidCapture(c)
File "interface/larry5.py", line 33, in vidCapture
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
cv2.error: OpenCV(4.5.4-dev) /tmp/pip-req-build-6qnmwb6g/opencv/modules/imgproc/src/color.cpp:182:
error: (-215:Assertion failed) !_src.empty() in function 'cvtColor'
My cameras are running at 10fps with a resolution of 176x144 using IPcam on two Samsung phones. I code below uses a database to switch cameras using OpenCV.
import cv2
import sqlite3
from datetime import datetime
connection = sqlite3.connect("/home/harry/interface/wildlife.db")
cursor = connection.cursor()
x = 1
c = 1
streamTarget = ''
def activityScan(status,c):
sql=cursor.execute("SELECT * FROM heavenStream WHERE id = ?",(c,))
dbstatus = sql.fetchone()
if(dbstatus[8]!=status):
putMoe=(status,c)
cursor.execute("UPDATE heavenStream SET streamTime =? where id=?", putMoe)
connection.commit()
def xmlFile(c):
row=cursor.execute("SELECT * FROM heavenStream WHERE id = ?",(c,))
streamTarget = row.fetchone()
return streamTarget[2]
def ipAddress(c):
row=cursor.execute("SELECT * FROM heavenStream WHERE id = ?",(c,))
streamTarget = row.fetchone()
def vidCapture(c):
h=0
face_cascade = cv2.CascadeClassifier(xmlFile(c))
cap = cv2.VideoCapture(ipAddress(c))
# while 1:
ret, img = cap.read()
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
for (x, y, w, h) in faces:
cv2.rectangle(img, (x, y), (x + w, y + h), (255, 255, 0), 2)
roi_gray = gray[y:y + h, x:x + w]
roi_color = img[y:y + h, x:x + w]
if(h):
print("active")
activityScan("active",c)
else:
print("inactive")
activityScan("inactive",c)
cv2.imshow('img', img)
# if cv2.waitKey(1) & 0xFF == 27:
# break
cap.release()
# cv2.destroyAllWindows()
def sensorAddress(moe):
ab = int(datetime.today().strftime('%S'))
if (ab % 2) == 0 :
return moe
# print("...")
else:
y = last_id() - 1
if(moe >= y and y % 2 == 0):
moe = 1
return moe
# print(y)
elif(moe >= y and y % 2 !=0):
moe = 1
return moe
# print(".. .. --")
else:
moe = moe + 2
return moe
def last_id(): ### Last ID in database
sql = cursor.execute('SELECT max(id) FROM heavenStream')
max_id = sql.fetchone()[0]
return max_id
def moeValue(moe): ## Larry
if(moe == last_id()):
moe = 1
return sensorAddress(moe)
elif(moe == last_id() - 1 and moe % 2 != 0):
moe = 1
return sensorAddress(moe)
elif(moe % 2 ) == 0:
moe = moe + 1
return sensorAddress(moe)
else:
moe = moe + 2
return sensorAddress(moe)
while True:
row=cursor.execute("SELECT * FROM heavenStream WHERE id = ?",(x,))
streamTarget = row.fetchone()
if ('moe' == streamTarget[8]):
c = moeValue(streamTarget[0])
vidCapture(c)
lastDBrecord = last_id()
if(x >= lastDBrecord):
x = 1
else:
x = x + 1
It works fine for up to an hour then fails. I used the code from the following website, https://pythonprogramming.net/haar-cascade-face-eye-detection-python-opencv-tutorial/ , as a basis, though I only have one xml file. I am running the latest version of Linux Mint. Any comments will be much appreciated.
I have added if(ret == True): to the following and there have been no errors for six hours:
ret, img = cap.read()
if(ret == True):
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
for (x, y, w, h) in faces:
cv2.rectangle(img, (x, y), (x + w, y + h), (255, 255, 0), 2)
roi_gray = gray[y:y + h, x:x + w]
roi_color = img[y:y + h, x:x + w]
if(h):
print("active")
print(ret)
activityScan("active",c)
else:
print("inactive")
print(ret)
activityScan("inactive",c)

I don't understand what's wrong with my array

Here is my code. When a program sees a face, it must recognize it. My array of names takes data from the database. When I need to recognize I get the following error:
Traceback (most recent call last):
File "C:\Users\kolya\OneDrive\Рабочий стол\projectGUI\frecognition2.py", line 56, in <module>
id = names[id]
IndexError: list index out of range
my code:
import cv2
import numpy as np
import os
import pyodbc
import datetime
#Database
conn = pyodbc.connect(r'DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=C:\Users\kolya\OneDrive\Рабочий стол\projectGUI\DatabaseGUI.accdb;')
cursor = conn.cursor()
cursor.execute('SELECT User_Name FROM Students')
names = []
names = cursor.fetchall()
#///////////////////
#Logs
def markAttendance(name):
with open("Attendance.csv", "r+") as f:
names = f.readlines()
if name not in names:
now = datetime.datetime.now()
f.writelines(f'\n{name}, {now}')
recognizer = cv2.face.LBPHFaceRecognizer_create()
recognizer.read('trainer/trainer.yml')
cascadePath = "haarcascade_frontalface_default.xml"
faceCascade = cv2.CascadeClassifier(cascadePath);
font = cv2.FONT_HERSHEY_SIMPLEX
id = 0
cam = cv2.VideoCapture(0, cv2.CAP_DSHOW)
cam.set(3, 640) # Ширина
cam.set(4, 480) # Висота
#Мінімальний розмір вікна розпізнавання обличчя
minW = 0.01*cam.get(3)
minH = 0.01*cam.get(4)
while True:
ret, img = cam.read()
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
faces = faceCascade.detectMultiScale(
gray,
scaleFactor = 1.1,
minNeighbors = 4,
minSize = (int(minW), int(minH)),
)
for(x,y,w,h) in faces:
cv2.rectangle(img, (x,y), (x+w,y+h), (0,255,0), 2)
id, confidence = recognizer.predict(gray[y:y+h,x:x+w])
if (confidence < 80):
id = names[id]
else:
id = "Unkown"
cv2.putText(img, str(id), (x+5,y-5), font, 1, (255,255,255), 2)
markAttendance(id)
cv2.imshow('Camera',img)
k = cv2.waitKey(10) & 0xff
if k == 27:
break
print("\n [INFO] Exiting Program and cleanup stuff")
cam.release()
cv2.destroyAllWindows()
The error message "IndexError: list index out of range" means that the length of the array names is inferior to the integer id.
To understand this, just do at line 55:
print("index: ", id, "- length: ", len(names))
You will see that length <= index.

0 Python-Opencv error: error: (-215) scn == 3 || scn == 4 in function cvtColor [duplicate]

import numpy as np
import cv2
import thread, winsound
face_cascade = cv2.CascadeClassifier('C:\Users\Saddaqat\Desktop\Softwares\opencv\build\share\OpenCV\haarcascades\haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier('C:\Users\Saddaqat\Desktop\Softwares\opencv\build\share\OpenCV\haarcascades\haarcascade_eye.xml')
def beep():
for i in xrange(4):
winsound.Beep(1500, 250)
cam = cv2.VideoCapture(0)
count = 0
iters = 0
while(True):
ret, cur = cam.read()
gray = cv2.cvtColor(cur, cv2.COLOR_BGR2GRAY)
faces = face
_cascade.detectMultiScale(gray,scaleFactor = 1.1, minNeighbors=1, minSize=(10,10))
for (x,y,w,h) in faces:
#cv2.rectangle(cur,(x,y),(x+w,y+h),(255,0,0),2)
roi_gray = gray[y:y+h,x:x+w]
roi_color = cur[y:y+h,x:x+w]
eyes = eye_cascade.detectMultiScale(roi_gray)
if len(eyes) == 0:
print "Eyes closed"
else:
print "Eyes open"
count += len(eyes)
iters += 1
if iters == 2:
iters = 0
if count == 0:
print "Drowsiness Detected!!!"
thread.start_new_thread(beep,())
count = 0
for (ex,ey,ew,eh) in eyes:
cv2.rectangle(roi_color,(ex,ey),(ex+ew,ey+eh), (0,255,0),2)
cv2.imshow('frame', cur)
if cv2.waitKey(1) & 0xFF == ord('q'):
cv2.destroyAllWindows()
break
//
I am facing this error Kindly resolve this error . thanks and love in advance ;)
Traceback (most recent call last):
File "C:\Users\Saddaqat\Desktop\fatigue detection code", line 17, in <module>
gray = cv2.cvtColor(cur, cv2.COLOR_BGR2GRAY)
error: ..\..\..\..\opencv\modules\imgproc\src\color.cpp:3739: error: (-215) scn == 3 || scn == 4 in function cv::cvtColor
Well, for me it looks like the VideoCapture is not working. You should check after reading the image, if it could have read something:
ret, cur = cam.read()
if not ret:
print "VideoCapture read no frame."
break
If that's the case, there has been some answers here in SO that might help you, for example: OpenCV 2.4 VideoCapture not working on Windows
Basically, they say that you might have problems with the ffmpeg. Maybe you have to add it to Windows path, and/or rename it to have the OpenCV version on it.

error occurred when using cv2.imshow()

The task is, i take pictures from the camera, and i process pictures using cnns, and then display the pic with the result. But there is an error when i use opencv python interface to show the image(the os is the mac os):
while(1):
test_data = []
ret, frame = cap.read()
frame = cv2.imread('hello.jpg')
h, w, _ = frame.shape
img = copy.deepcopy(frame)
img = pre_process(img)
test_data.append([img])
ret_res = _infer(inferer, test_data, threshold)
draw_result(frame, ret_res, h, w)
cv2.imshow("hellocapture", frame)
the following error occurred:
PC: # 0x0 (unknown)
*** SIGFPE (#0x7fffc5186d01) received by PID 36436 (TID 0x7fffe38773c0) stack
trace: ***
# 0x7fffdab7bb3a _sigtramp
# 0x7fffc5186d02 CFNumberCreate
# 0x7fffc6c027b5 -[NSPlaceholderNumber initWithDouble:]
# 0x7fffcae3b594 +[CALayer defaultValueForKey:]
# 0x7fffcaebd489 classDescription_locked()
# 0x7fffcaebc9fe classDescription_locked()
# 0x7fffcaebc9fe classDescription_locked()
# 0x7fffcaeb8292 classDescription()
# 0x7fffcaeb8495 CAObject_classInfo
# 0x7fffcae3bdf4 CA::Layer::class_state()
# 0x7fffcae3e081 -[CALayer init]
# 0x7fffc2d07854 -[NSView makeBackingLayer]
# 0x7fffc2d076db -[NSView(NSInternal) _createLayerAndInitialize]
# 0x7fffc2d06d4d -[NSView _doSetWantsLayerYES]
# 0x7fffc2d069da -[NSView setWantsLayer:]
# 0x7fffc2d142b6 __49-[NSThemeFrame _floatTitlebarAndToolbarFromInit:]_block_invoke
# 0x7fffc364b8b6 +[NSAnimationContext runAnimationGroup:]
# 0x7fffc2d13f23 -[NSThemeFrame _floatTitlebarAndToolbarFromInit:]
# 0x7fffc2d11a9c -[NSThemeFrame initWithFrame:styleMask:owner:]
# 0x7fffc2d10522 -[NSWindow _commonInitFrame:styleMask:backing:defer:]
# 0x7fffc2d0ec03 -[NSWindow _initContent:styleMask:backing:defer:contentView:]
# 0x7fffc2d0e65f -[NSWindow initWithContentRect:styleMask:backing:defer:]
# 0x1171ddebd -[QCocoaWindow initWithContentRect:styleMask:backing:defer:]
# 0x1171dddb1 -[NSWindow(QWidgetIntegration) qt_initWithQWidget:contentRect:styleMask:]
# 0x1171cee19 qt_mac_create_window()
# 0x1171ce119 QWidgetPrivate::createWindow_sys()
# 0x1171ce073 qt_mac_window_for()
# 0x1171d3b13 QWidgetPrivate::setModal_sys()
# 0x1172637c8 QWidget::create()
# 0x1175d5431 QToolBarPrivate::init()
# 0x1175d631c QToolBar::QToolBar()
# 0x111ca9c98 CvWindow::createToolBar()
Floating point exception: 8
and i've positioned that the cv2.imshow has the problem, but i don't know how?
if i just use the folloing code, it's ok
#!/usr/bin/env python
# coding=utf-8
import cv2
import numpy
import matplotlib.pyplot as plot
cap = cv2.VideoCapture(0)
while(1):
# get a frame
ret, frame = cap.read()
# show a frame
print frame.shape
cv2.imshow("capture", frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
When you display an image in OpenCV you normally need to set a waitKey and release:
while(1):
test_data = []
ret, frame = cap.read()
frame = cv2.imread('hello.jpg')
h, w, _ = frame.shape
img = copy.deepcopy(frame)
img = pre_process(img)
test_data.append([img])
ret_res = _infer(inferer, test_data, threshold)
draw_result(frame, ret_res, h, w)
cv2.imshow("hellocapture", frame)
if cv2.waitKey(1) & 0xFF == ord('q')
break
cap.release()
cv2.destroyAllWindows()

OpenCV_TypeError: 'NoneType' object has no attribute '__getitem__'

I was using OpenCV 2.4.6 and was running the following code successfully from OpenCV Python Tutorial-
import numpy as np
import cv2
cap = cv2.VideoCapture('slow.flv')
ret,frame = cap.read()
r,h,c,w = 250,90,400,125 # simply hardcoded the values
track_window = (c,r,w,h)
roi = frame[r:r+h, c:c+w]
hsv_roi = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
mask = cv2.inRange(hsv_roi, np.array((0., 60.,32.)), np.array((180.,255.,255.)))
roi_hist = cv2.calcHist([hsv_roi],[0],mask,[180],[0,180])
cv2.normalize(roi_hist,roi_hist,0,255,cv2.NORM_MINMAX)
term_crit = ( cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 10, 1 )
while(1):
ret ,frame = cap.read()
if ret == True:
hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
dst = cv2.calcBackProject([hsv],[0],roi_hist,[0,180],1)
# apply meanshift to get the new location
ret, track_window = cv2.meanShift(dst, track_window, term_crit)
# Draw it on image
x,y,w,h = track_window
img2 = cv2.rectangle(frame, (x,y), (x+w,y+h), 255,2)
cv2.imshow('img2',img2)
k = cv2.waitKey(60) & 0xff
if k == 27:
break
else:
cv2.imwrite(chr(k)+".jpg",img2)
else:
break
cv2.destroyAllWindows()
cap.release()
Later on I started to using OpenCV 3.0 and replace some Lib files in site packages directory and also replaced CV2.pyd file.Then when I tried to run the same code, i am getting the following error-
Traceback (most recent call last):
File "D:\Backup\OpenCV_Python_Prac_files\Prac5.1.1_ Video Analysis_MeanShift.py", line 14, in
roi = frame[r:r+h, c:c+w]
TypeError: 'NoneType' object has no attribute '_getitem_'
Can anyone tell me what is the reason behind causing this problem?
Thanks in Advance.
The error says that your frame is None. Check the return value of the first call to cap.read

Categories