error: (-215) nimages > 0 in function calibrateCamera using Python and OpenCV - python

I'm trying to calibrate my web-cam based on the example given in the opencv samples but when i run the code provided here:
def caliLeftCam():
args, img_mask = getopt.getopt(sys.argv[1:], '', ['save=', 'debug=', 'square_size='])
args = dict(args)
try: img_mask = img_mask[0]
except: img_mask = '../cpp/img*.jpg'
img_names = glob(img_mask)
debug_dir = args.get('--debug')
square_size = float(args.get('--square_size', 1.0))
pattern_size = (7, 5)
pattern_points = np.zeros( (np.prod(pattern_size), 3), np.float32 )
pattern_points[:,:2] = np.indices(pattern_size).T.reshape(-1, 2)
pattern_points *= square_size
obj_points = []
img_pointsL = []
h, w = 0, 0
for fn in img_names:
print "processing %s..." % fn,
imgL = cv2.imread(fn, 0)
h, w = imgL.shape[:2]
found, corners = cv2.findChessboardCorners(imgL, pattern_size)
if found:
term = ( cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_COUNT, 30, 0.1 )
cv2.cornerSubPix(imgL, corners, (5, 5), (-1, -1), term)
if debug_dir:
vis = cv2.cvtColor(imgL, cv2.COLOR_GRAY2BGR)
cv2.drawChessboardCorners(vis, pattern_size, corners, found)
path, name, ext = splitfn(fn)
cv2.imwrite('%s/%s_chess.bmp' % (debug_dir, name), vis)
if not found:
print "chessboard not found"
continue
img_pointsL.append(corners.reshape(-1, 2))
obj_points.append(pattern_points)
print 'ok'
rmsL, cameraL_matrix, dist_coefsL, rvecsL, tvecsL = cv2.calibrateCamera(obj_points, img_pointsL, (w, h))
i got this error:
Traceback (most recent call last):
File "/home/sabrine/Downloads/opencv-2.4.9/samples/python2/Memo.py", line 293, in <module>
Img_pointsL, Cam_MatL, DisL = caliLeftCam()
File "/home/sabrine/Downloads/opencv-2.4.9/samples/python2/Memo.py", line 124, in caliLeftCam
rmsL, cameraL_matrix, dist_coefsL, rvecsL, tvecsL = cv2.calibrateCamera(obj_points, img_pointsL, (w, h))
error: /build/buildd/opencv-2.4.8+dfsg1/modules/calib3d/src/calibration.cpp:3415:
error: (-215) nimages > 0 in function calibrateCamera
what does this error mean?
and how can i solve it?

The error says that one of the vectors provided as arguments is empty.
The function has an assertion that prevents You from using it, if not all conditions are met. This time it checks if there are enough image points (nimages > 0 must be true).

Recheck the value of nx and ny (pattern_size) for the function "cv2.findChessboardCorners(image, (nx, ny))/ cv2.drawChessboardCorners(image, pattern_size)", this should be number of inner corners row and column in the chessboard. It worked for me.

I know I am too late, but hope it helps other people. Replace the following line:
except: img_mask = '../cpp/img*.jpg'
with:
except: img_mask = './cpp/img*.jpg'

In my case I was not using a big enough checkerboard in the sample pictures. Printing a 7x10 checkerboard instead than 6x7 solved it.

import numpy as np
import cv2
cap = cv2.VideoCapture('output.avi')
i=1
while(cap.isOpened()):
ret, img = cap.read()
print img
if img==None:#sale el error por que ya termino los frames del video
break #si no hay frames, terminarel programa
cv2.imshow('img2',img)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
elif cv2.waitKey(1) & 0xFF==ord('p'):
cv2.imwrite('image'+str(i)+'.jpg',img)
i=i+1
cap.release()
cv2.destroyAllWindows()

Related

TypeError: Only Size-1 Arrays Can Be Converted To Python Scalars Error

The error is Only Size-1 Arrays Can Be Converted To Python Scalars Error and i just fixed the problem regarding the sizing. But now I'm running this code with a 320x320 model but I'm still receiving this error does anyone know how to fix it? I've been receiving errors on lines 45, 68, 88 but I'm not sure what to change in them?
import cv2
from tflite_runtime.interpreter import Interpreter
import numpy as np
CAMERA_WIDTH = 640
CAMERA_HEIGHT = 480
def load_labels(path='labels.txt'):
"""Loads the labels file. Supports files with or without index numbers."""
with open(path, 'r', encoding='utf-8') as f:
lines = f.readlines()
labels = {}
for row_number, content in enumerate(lines):
pair = re.split(r'[:\s]+', content.strip(), maxsplit=1)
if len(pair) == 2 and pair[0].strip().isdigit():
labels[int(pair[0])] = pair[1].strip()
else:
labels[row_number] = pair[0].strip()
return labels
def set_input_tensor(interpreter, image):
"""Sets the input tensor."""
tensor_index = interpreter.get_input_details()[0]['index']
input_tensor = interpreter.tensor(tensor_index)()[0]
input_tensor[:, :] = np.expand_dims((image-255)/255, axis=0)
def get_output_tensor(interpreter, index):
"""Returns the output tensor at the given index."""
output_details = interpreter.get_output_details()[index]
tensor = np.squeeze(interpreter.get_tensor(output_details['index']))
return tensor
def detect_objects(interpreter, image, threshold):
"""Returns a list of detection results, each a dictionary of object info."""
set_input_tensor(interpreter, image)
interpreter.invoke()
# Get all output details
boxes = get_output_tensor(interpreter, 0)
classes = get_output_tensor(interpreter, 1)
scores = get_output_tensor(interpreter, 2)
count = int(get_output_tensor(interpreter, 3))
results = []
for i in range(count):
if scores[i] >= threshold:
result = {
'bounding_box': boxes[i],
'class_id': classes[i],
'score': scores[i]
}
results.append(result)
return results
def main():
labels = load_labels()
interpreter = Interpreter('detect.tflite')
interpreter.allocate_tensors()
_, input_height, input_width, _ = interpreter.get_input_details()[0]['shape']
cap = cv2.VideoCapture(0)
while cap.isOpened():
ret, frame = cap.read()
img = cv2.resize(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB), (320,320))
res = detect_objects(interpreter, img, 0.8)
print(res)
for result in res:
ymin, xmin, ymax, xmax = result['bounding_box']
xmin = int(max(1,xmin * CAMERA_WIDTH))
xmax = int(min(CAMERA_WIDTH, xmax * CAMERA_WIDTH))
ymin = int(max(1, ymin * CAMERA_HEIGHT))
ymax = int(min(CAMERA_HEIGHT, ymax * CAMERA_HEIGHT))
cv2.rectangle(frame,(xmin, ymin),(xmax, ymax),(0,255,0),3)
cv2.putText(frame,labels[int(result['class_id'])],(xmin, min(ymax, CAMERA_HEIGHT-20)), cv2.FONT_HERSHEY_SIMPLEX, 0.5,(255,255,255),2,cv2.LINE_AA)
cv2.imshow('Pi Feed', frame)
if cv2.waitKey(10) & 0xFF ==ord('q'):
cap.release()
cv2.destroyAllWindows()
if __name__ == "__main__":
main()```
I've tried changing some sections in line 45 and 88 to it gives me the same error.

Image Classifire feature detector

I have a code that I learn from this link https://www.youtube.com/watch?v=nnH55-zD38I&t=1047s
but I got an error that said:
line 62, in <module>
cv2.putText(imgOriginal,classNames[id], (50,50),cv2.FONT_HERSHEY_COMPLEX,1,(0,255,0),1)
IndexError: list index out of range
[ WARN:0] global C:\Users\runneradmin\AppData\Local\Temp\pip-req-build-m8us58q4\opencv\modules\videoio\src\cap_msmf.cpp
(438) `anonymous-namespace'::SourceReaderCB::~SourceReaderCB terminating async callback
Here is the code:
import cv2
import numpy as np
import os
path = '#2 Image descriptor\Assets\Query'
orb = cv2.ORB_create(nfeatures=1000)
#IMPORT IMAGES
images = []
classNames = []
myList = os.listdir(path)
print('Jumlah Classes = ', len(myList))
#print(myList)
for cl in myList:
imgCur = cv2.imread(f'{path}/{cl}', 0)
images.append(imgCur)
classNames.append(os.path.splitext(cl)[0])
print (classNames)
def findDes(images) :
desList = []
for img in images :
kp, des = orb.detectAndCompute(img, None)
desList.append(des)
return desList
def findID(img, desList, thres=15):
kp2, des2 = orb.detectAndCompute(img, None)
bf = cv2.BFMatcher()
matchList = []
finalVal = -1
try :
for des in desList:
matches = bf.knnMatch(des, des2, k=2)
good = []
for m, n in matches:
if m.distance < 0.7*n.distance:
good.append([m])
matchList.append(len(good))
except :
pass
#print(matchList)
if len(matchList) != 0:
if max(matchList) > thres:
finalVal = matchList.index(max(matchList))
return finalVal
desList = findDes(images)
print(len(desList))
cap = cv2.VideoCapture(0)
#cap = cv2.imread('#2 Image descriptor\Assets\Train\RE8.jpg')
while True:
success, img2 = cap.read()
imgOriginal = img2.copy()
img2 = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)
id = findID(img2, desList)
if id != -1:
cv2.putText(imgOriginal,classNames[id], (50,50),cv2.FONT_HERSHEY_COMPLEX,1,(0,255,0),1)
cv2.imshow('img2', imgOriginal)
if cv2.waitKey(1) == ord('q'):
break
cap.release() #to make sure disable the camera from the code
cv2.destroyAllWindows
I think the error at:
imgCur = cv2.imread(f'{path}/{cl}', 0)
The problem is at this part of your code:
if id != -1:
cv2.putText(imgOriginal,classNames[id], (50,50),cv2.FONT_HERSHEY_COMPLEX,1,(0,255,0),1)
The error is basically telling you that you are trying to index id from the classNames list at an index that doesn't exist in the list. For example, if the classNames list is empty, doing classNames[0] will return the error. You can try debugging like so:
if id != -1:
if id < len(classNames):
cv2.putText(imgOriginal,classNames[id], (50,50),cv2.FONT_HERSHEY_COMPLEX,1,(0,255,0),1)
else:
print(classNames)
print(f"Error: Attempted to index {id} from list of length {len(classNames)}.")

TypeError: cannot unpack non-iterable numpy.float64 object

The below piece of code uses openCV module to identify lanes on road. I use the python 3.6 for coding (I use atom IDE for development. This info is being provided because stackoverflow isn't letting me post the info without unnecessary lines of info. so please ignore the comments in bracket)
The code runs fine with a given sample video. But when I run it for another video it throws the following error:
(base) D:\Self-Driving course\finding-lanes>RayanFindingLanes.py
C:\Users\Tarun\Anaconda3\lib\site-packages\numpy\lib\function_base.py:392: RuntimeWarning: Mean of empty slice.
avg = a.mean(axis)
C:\Users\Tarun\Anaconda3\lib\site-packages\numpy\core\_methods.py:85: RuntimeWarning: invalid value encountered in double_scalars
ret = ret.dtype.type(ret / rcount)
Traceback (most recent call last):
File "D:\Self-Driving course\finding-lanes\RayanFindinglanes.py", line 81, in <module>
averaged_lines = average_slope_intercept(frame, lines)
File "D:\Self-Driving course\finding-lanes\RayanFindinglanes.py", line 51, in average_slope_intercept
right_line = make_points(image, right_fit_average)
File "D:\Self-Driving course\finding-lanes\RayanFindinglanes.py", line 56, in make_points
slope, intercept = line
TypeError: cannot unpack non-iterable numpy.float64 object
What does the error mean and how to solve it?
code:
import cv2
import numpy as np
def canny(img):
gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
kernel = 5
blur = cv2.GaussianBlur(gray,(kernel, kernel),0)
canny = cv2.Canny(blur, 50, 150)
return canny
def region_of_interest(canny):
height = canny.shape[0]
width = canny.shape[1]
mask = np.zeros_like(canny)
triangle = np.array([[
(200, height),
(550, 250),
(1100, height),]], np.int32)
cv2.fillPoly(mask, triangle, 255)
masked_image = cv2.bitwise_and(canny, mask)
return masked_image
def display_lines(img,lines):
line_image = np.zeros_like(img)
if lines is not None:
for line in lines:
for x1, y1, x2, y2 in line:
cv2.line(line_image,(x1,y1),(x2,y2),(255,0,0),10)
return line_image
def average_slope_intercept(image, lines):
left_fit = []
right_fit = []
if lines is None:
return None
for line in lines:
for x1, y1, x2, y2 in line:
fit = np.polyfit((x1,x2), (y1,y2), 1)
slope = fit[0]
intercept = fit[1]
if slope < 0: # y is reversed in image
left_fit.append((slope, intercept))
else:
right_fit.append((slope, intercept))
# add more weight to longer lines
left_fit_average = np.average(left_fit, axis=0)
right_fit_average = np.average(right_fit, axis=0)
left_line = make_points(image, left_fit_average)
right_line = make_points(image, right_fit_average)
averaged_lines = [left_line, right_line]
return averaged_lines
def make_points(image, line):
slope, intercept = line
y1 = int(image.shape[0])# bottom of the image
y2 = int(y1*3/5) # slightly lower than the middle
x1 = int((y1 - intercept)/slope)
x2 = int((y2 - intercept)/slope)
return [[x1, y1, x2, y2]]
cap = cv2.VideoCapture("test3.mp4")
while(cap.isOpened()):
_, frame = cap.read()
canny_image = canny(frame)
cropped_canny = region_of_interest(canny_image)
lines = cv2.HoughLinesP(cropped_canny, 2, np.pi/180, 100, np.array([]), minLineLength=40,maxLineGap=5)
averaged_lines = average_slope_intercept(frame, lines)
line_image = display_lines(frame, averaged_lines)
combo_image = cv2.addWeighted(frame, 0.8, line_image, 1, 1)
cv2.imshow("result", combo_image)
if cv2.waitKey(1) == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
In some of the frames all the slope are > 0 hence left_fit list is empty. Because of that you are getting error when you are calculating left_fit average. One of the way to solve this problem to use left_fit average from previous frame. I have solved it using the same approach. Please see the code below and let me know if it has solved your issue.
global_left_fit_average = []
global_right_fit_average = []
def average_slope_intercept(image, lines):
left_fit = []
right_fit = []
global global_left_fit_average
global global_right_fit_average
if lines is not None:
for line in lines:
x1, y1, x2, y2 = line.reshape(4)
parameters = np.polyfit((x1, x2), (y1,y2), 1)
slope = parameters[0]
intercept = parameters[1]
if (slope < 0):
left_fit.append((slope, intercept))
else:
right_fit.append((slope, intercept))
if (len(left_fit) == 0):
left_fit_average = global_left_fit_average
else:
left_fit_average = np.average(left_fit, axis=0)
global_left_fit_average = left_fit_average
right_fit_average = np.average(right_fit, axis=0)
global_right_fit_average = right_fit_average
left_line = make_corordinates(image, left_fit_average)
right_line = make_corordinates(image, right_fit_average)
return np.array([left_line, right_line])
HoughLinesP returns a list and that can be an empty list and not necessarily None
So the lines in the function average_slope_intercept
if lines is None:
return None
is not much of use.
You need to check len(lines) == 0

NameError even when variable is initialize

I'm coding on Python (first timer) trying to program an artificial vision algorithm which recognizes when a TV channel is showing a spot or a regular TV show (there are no TV logos when a spot is running on TV).
The code I'm working with is this
import numpy as np
import cv2
cap = cv2.VideoCapture('Telecinco.mp4')
count = 0
template = cv2.imread('telecinco_logo.png',0)
while(cap.isOpened()):
ret, frame = cap.read()
frame = cv2.resize(frame,None,fx=1,fy=1,interpolation = cv2.INTER_CUBIC)
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
if count == 0:
count = 1
cv2.imwrite('image.png', frame)
w, h = template.shape[::-1]
res = cv2.matchTemplate(gray,template,cv2.TM_CCOEFF_NORMED)
threshold = 0.7
loc = np.where( res >= threshold)
for pt in zip(*loc[::-1]):
logo_img = frame[pt[1]:pt[1]+h,pt[0]:pt[0]+w]
cv2.rectangle(frame, pt, (pt[0] + w, pt[1] + h), (0, 0, 255), 1)
cv2.imshow('Captura',frame)
cv2.imshow('Logo encontrado', logo_img)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
However, python is giving me an error:
Traceback (most recent call last):
File "logoDeteccion.py", line 27, in <module>
cv2.imshow('Logo encontrado', logo_img)
NameError: name 'logo_img' is not defined
And I'm really confused. logo_img is always declared (or should be). When commenting that line program is running fine, but of course doesn't do what it should do.
Any ideas?
Thanks!
Inside the while loop, you try to show logo_img to the screen.
If it does not exists, then you can wait for zip(*loc[::-1]) to have an actual value.
See the code below:
while(cap.isOpened()):
try:
cv2.imshow('Logo encontrado', logo_img)
except NameError:
pass #Go for next loop and check to see if logo_img exists

Python OpenCV Error

Simple Code used to identify playing cards through a cam but I have Been trying to run this code but I keep getting this error when attempting to use any of the methods
TypeError: src is not a numpy array, neither a scalar
import sys
import numpy as np
sys.path.insert(0, "/usr/local/lib/python2.7/site-packages/")
import cv2
###############################################################################
# Utility code
###############################################################################
def rectify(h):
h = h.reshape((4,2))
hnew = np.zeros((4,2),dtype = np.float32)
add = h.sum(1)
hnew[0] = h[np.argmin(add)]
hnew[2] = h[np.argmax(add)]
diff = np.diff(h,axis = 1)
hnew[1] = h[np.argmin(diff)]
hnew[3] = h[np.argmax(diff)]
return hnew
###############################################################################
# Image Matching
###############################################################################
def preprocess(img):
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray,(5,5),2 )
thresh = cv2.adaptiveThreshold(blur,255,1,1,11,1)
return thresh
def imgdiff(img1,img2):
img1 = cv2.GaussianBlur(img1,(5,5),5)
img2 = cv2.GaussianBlur(img2,(5,5),5)
diff = cv2.absdiff(img1,img2)
diff = cv2.GaussianBlur(diff,(5,5),5)
flag, diff = cv2.threshold(diff, 200, 255, cv2.THRESH_BINARY)
return np.sum(diff)
def find_closest_card(training,img):
features = preprocess(img)
return sorted(training.values(), key=lambda x:imgdiff(x[1],features))[0][0]
###############################################################################
# Card Extraction
###############################################################################
def getCards(im, numcards=4):
gray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray,(1,1),1000)
flag, thresh = cv2.threshold(blur, 120, 255, cv2.THRESH_BINARY)
contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
contours = sorted(contours, key=cv2.contourArea,reverse=True)[:numcards]
for card in contours:
peri = cv2.arcLength(card,True)
approx = rectify(cv2.approxPolyDP(card,0.02*peri,True))
# box = np.int0(approx)
# cv2.drawContours(im,[box],0,(255,255,0),6)
# imx = cv2.resize(im,(1000,600))
# cv2.imshow('a',imx)
h = np.array([ [0,0],[449,0],[449,449],[0,449] ],np.float32)
transform = cv2.getPerspectiveTransform(approx,h)
warp = cv2.warpPerspective(im,transform,(450,450))
yield warp
def get_training(training_labels_filename,training_image_filename,num_training_cards,avoid_cards=None):
training = {}
labels = {}
for line in file(training_labels_filename):
key, num, suit = line.strip().split()
labels[int(key)] = (num,suit)
print "Training"
im = cv2.imread(training_image_filename)
for i,c in enumerate(getCards(im,num_training_cards)):
if avoid_cards is None or (labels[i][0] not in avoid_cards[0] and labels[i][1] not in avoid_cards[1]):
training[i] = (labels[i], preprocess(c))
print "Done training"
return training
if __name__ == '__main__':
if len(sys.argv) == 6:
filename = sys.argv[1]
num_cards = int(sys.argv[2])
training_image_filename = sys.argv[3]
training_labels_filename = sys.argv[4]
num_training_cards = int(sys.argv[5])
training = get_training(training_labels_filename,training_image_filename,num_training_cards)
im = cv2.imread("test")
width = im.shape[0]
height = im.shape[1]
if width < height:
im = cv2.transpose(im)
im = cv2.flip(im,1)
# Debug: uncomment to see registered images
#for i,c in enumerate(getCards(im,num_cards)):
# card = find_closest_card(training,c,)
# cv2.imshow(str(card),c)
# cv2.waitKey(0)
cards = [find_closest_card(training,c) for c in getCards(im,num_cards)]
print cards
else:
print __doc__
here is the entire error message
Traceback (most recent call last):
File "<pyshell#15>", line 1, in <module>
preprocess("test.JPG")
File "C:\Users\Don Ellison\Desktop\Class Programs\CSC 490 Project\Cards\Python\Playing-Card-Recognition-master\card_img.py", line 43, in preprocess
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
TypeError: src is not a numpy array, neither a scalar
you are passing in wrong argument to preprocess function, I guess you are calling it from a python shell.
You are not suppose to pass in a image file name, but rather a numpy array. It seems you called proprocess function and passed in "test.JPG" in your python shell. If you want to test your preprocess function, do
test_img = cv2.imread("test.JPG")
preprocess(test_img)

Categories