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

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.

Related

Data not recorded from second item onwards in excel using Python

I am currently doing a inventory management system using python and excel. The first item records just fine, but when I try scanning the 2nd item in the list it keeps saying "Item has been borrowed" eventhough its not borrowed yet. Each item has a unique QR code too.
Below is my code:
#CODE FOR BORROW
import PySimpleGUI as sg
import pandas as pd
import cv2
import pyzbar.pyzbar as zbar
import time
import datetime
import openpyxl
import subprocess
from openpyxl import load_workbook, Workbook
sg.popup('Please scan your Employee ID', title = "Borrow")
cap = cv2.VideoCapture(0)
font = cv2.FONT_HERSHEY_SIMPLEX
stopped = False
l=0
while(True):
key = cv2.waitKey(1)
if key == 27:
break
ret = cv2.waitKey(1) & 0xFF
# Capture frame-by-frame
ret, frame = cap.read()
decodedObjects = zbar.decode(frame)
if len(decodedObjects) > 0:
stopped = True
for obj in decodedObjects:
Employee_ID = obj.data.decode("utf-8")
cv2.putText(frame,Employee_ID, (50, 100), font, 2, (0, 0, 255), 3)
l+=1
# Display the resulting frame
cv2.imshow('Scan Employee ID',frame)
if l == 1:
cv2.waitKey(1)
time.sleep(2)
cv2.destroyAllWindows()
break
sg.popup('Please scan your Item ID', title = "Borrow")
cap = cv2.VideoCapture(0)
font = cv2.FONT_HERSHEY_SIMPLEX
stopped = False
l=0
while(True):
ret = cv2.waitKey(1) & 0xFF
# Capture frame-by-frame
ret, frame = cap.read()
decodedObjects = zbar.decode(frame)
if len(decodedObjects) > 0:
stopped = True
for obj in decodedObjects:
Borrow = obj.data.decode("utf-8")
cv2.putText(frame,Borrow, (50, 100), font, 2, (0, 0, 255), 3)
l+=1
# Display the resulting frame
cv2.imshow('Scan Item ID',frame)
if l == 1:
cv2.waitKey(1)
time.sleep(2)
cv2.destroyAllWindows()
break
wb=openpyxl.load_workbook(filename = r"C:\PROJECT\RIS\RIS\RIS.xlsx")
ws = wb.active
search_item = Borrow
for i in range(1, ws.max_row + 1):
for j in range(1, ws.max_column + 1):
if search_item == ws.cell(i,j).value:
location=(ws.cell(i,j+3).value)
if location:
# Define Excel File Path
RIS = r"C:\PROJECT\RIS\RIS\RIS.xlsx"
df_RIS = pd.read_excel(RIS)
time = datetime.datetime.now().strftime('%d-%m-%Y %H:%M:%S')
df_RIS.loc[df_RIS.SERIAL_NUMBER == Borrow, ['DATE_BORROW', 'STATUS_BORROW','DATE_RETURN', 'STATUS_RETURN']] = time, Employee_ID, "", ""
df_RIS.to_excel(RIS, index=False)
sg.popup('Borrowed item has been recorded successfully!', title = "Access Granted !")
subprocess.call([r"C:\PROJECT\RIS\RIS\RIS_test1.bat"])
else:
sg.popup('The above item has been borrowed.', title = "Error !")
My excel file for the item data :
Can I know how to resolve this? Thanks so much.
I tried naming the item under category differently but still dosent solve anything.

Detecting water in a plant stem in real time using computer vision (OpenCV and Python)

I am working on an experiment with plants in a pressure chamber. I need to be able to identify with a computer vision algorithm the exact moment when water starts to appear at the cut end of the stem. In the case of this video - taken from a USB microscope, this is the interval between 0:30 and 0:34 seconds, approximately.
I tried to use MOG, MOG2 and GMG as a background subtractor, and compare the histograms of each frame (using chi-squared, bhattacharyya, correlation), looking for changes that could be significant, however still without success. Is there a better alternative for this type of work?
Below, some code (made with the help of a friend)
import numpy as np
import sys
import time
import cv2
from matplotlib import pyplot as plt
video_filename = 'M20201022_004.mov'
capture = cv2.VideoCapture(video_filename)
#fgbg = cv2.bgsegm.createBackgroundSubtractorMOG()
fgbg = cv2.createBackgroundSubtractorMOG2()
#kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(3,3))
#fgbg = cv2.bgsegm.createBackgroundSubtractorGMG()
width = int(capture.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(capture.get(cv2.CAP_PROP_FRAME_HEIGHT))
frames_per_second = capture.get(cv2.CAP_PROP_FPS)
num_frames = int(capture.get(cv2.CAP_PROP_FRAME_COUNT))
print(' height: {}\n width: {}\n fps: {}\n num_frames: {}\n'.format(height, width,frames_per_second, num_frames))
frameCounter = 0
t = time.process_time()
dist_hist = 0 # distance between histograms
frame_hist = 0
time_hist = 0
#write file
file1 = open("resultado.txt","w")
if not capture.isOpened():
print("Could not open video")
print('frameCounter: {}'.format(frameCounter))
sys.exit(1)
while capture.isOpened():
success, frame = capture.read()
frameCounter += 1
# Test for read error
if not success:
print('Failed to read video - Video Capture EOF or Error')
print('frameCounter:{}'.format(frameCounter))
if frameCounter == num_frames + 1:
print('EOF found')
else:
print('error')
break
#sys.exit(1)
else:
if frameCounter % 1000 == 0:
print('type:{} size:{} dtype:{} len(shape):{} contador:{}'.format(type(frame),frame.size,frame.dtype,len(frame.shape),frameCounter))
if len(frame.shape) < 3: # grayscale
h, w = frame.shape
print('h:{} w:{}'.format(h, w))
else: # color image
h, w, ch = frame.shape
print('h:{} w:{} ch:{}'.format(h, w, ch))
fgmask = fgbg.apply(frame)
#fgmask = fgbg.apply(frame)
#fgmask = cv2.morphologyEx(fgmask, cv2.MORPH_OPEN, kernel)
# Initial histogram Test
if frameCounter == 1:
hist_initial = cv2.calcHist([fgmask], [0],None,[16],[0, 256])
# print('hist_initial:{}'.format(hist_initial))
#elapsed_time = time.process_time() - t
elapsed_time = frameCounter / frames_per_second
# Process Histogram
hist_process = cv2.calcHist([fgmask], [0],None,[16],[0, 256])
dist = cv2.compareHist(hist_initial, hist_process,cv2.HISTCMP_CHISQR)
str1 = str(frameCounter) + "," + str(dist) + "," + str(dist_hist) + "," + str(elapsed_time)
file1.write(str1)
file1.write("\n")
if dist > dist_hist: # Depending on compareHist method
dist_hist = dist
time_hist = elapsed_time
frame_hist = frameCounter
# Print line at image
strfmt = 'frame: {} elapsed_time: {:7.2f}'.format(frameCounter, elapsed_time)
cv2.putText(frame, strfmt, (0, 50),cv2.FONT_HERSHEY_COMPLEX_SMALL, 1, (0,0,255), 1, cv2.LINE_AA)
cv2.imshow('frame', frame)
cv2.imshow('fgmask', fgmask)
if cv2.waitKey(1) & 0xff == 27: # ESC pressed
break
print('---> frame:{} dist:{:10.6f} time:{:7.2f}'.format(frame_hist, dist_hist,time_hist))
capture.release()
cv2.destroyAllWindows()
file1.close()
Any help appreciated!

AttributeError: 'dict' python opencv and openalpr

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()

Opencv python background substraction and motion tracking

I read about opencv on google and found the following sample code online to play with:
import cv2
def diffImg(t0, t1, t2):
d1 = cv2.absdiff(t2, t1)
d2 = cv2.absdiff(t1, t0)
return cv2.bitwise_and(d1, d2)
cam = cv2.VideoCapture('vid1.mp4')
winName = "Movement Indicator"
cv2.namedWindow(winName, cv2.CV_WINDOW_AUTOSIZE)
# Read three images first:
t_minus = cv2.cvtColor(cam.read()[1], cv2.COLOR_RGB2GRAY)
t = cv2.cvtColor(cam.read()[1], cv2.COLOR_RGB2GRAY)
t_plus = cv2.cvtColor(cam.read()[1], cv2.COLOR_RGB2GRAY)
while True:
cv2.imshow( winName, diffImg(t_minus, t, t_plus) )
# Read next image
t_minus = t
t = t_plus
t_plus = cv2.cvtColor(cam.read()[1], cv2.COLOR_RGB2GRAY)
key = cv2.waitKey(10)
if key == 27:
cv2.destroyWindow(winName)
break
print "Goodbye"
It produces the following kind of output for a sample video that I give to it:
So I am getting such results with this script. Now what I am trying to figure out is -
1) Get the bounding rect for the moving object in the video file
2) copy the contents of that bounding rect from original video frame to another and write the finished video to a file
Also, the screenshots on trying Kanishak Katahra's solution below I am getting the following output in the result window in the right side in the screenshot below -
Make the point of interest in the output you are getting as 1s. Make the rest as 0.
Convert it to 3D array of size same as original image.
Multiply original image with the output you are getting.
import cv2
import numpy as np
from numpy import newaxis
import time
def diffimg (a,b,c):
t0 = cv2.absdiff(a,b)
t1 = cv2.absdiff(b,c)
t3 = cv2.bitwise_and(t0,t1)
return t3
cap = cv2.VideoCapture(0)
t = cap.read() [1]
tp = cap.read() [1]
tpp = cap.read() [1]
t = cv2.cvtColor(t,cv2.COLOR_BGR2GRAY)
tp = cv2.cvtColor(tp,cv2.COLOR_BGR2GRAY)
tpp = cv2.cvtColor(tpp,cv2.COLOR_BGR2GRAY)
while True:
img = diffimg(t,tp,tpp)
cv2.imshow("motion detct",img)
key = cv2.waitKey(10)
res,img2 = cap.read()
#print img2.shape
t = tp
tp = tpp
tpp = cv2.cvtColor(img2,cv2.COLOR_BGR2GRAY)
cv2.imshow('image',img)
print img
img[img <= 10] = 0 #Try adjusting this value for better results.
img[img != 0] = 1
img = np.repeat(img[:, :, np.newaxis], 3, axis=2)
img3 = np.multiply( img,img2)
cv2.imshow('result',img3)
if key == 27:
cv2.destroyAllWindows()
break;
print "Goodbye User"

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