How can i fix this? OpenCV(4.6.0) /io/opencv/modules/imgproc/src/color.cpp:182: error: (-215:Assertion failed) !_src.empty() in function 'cvtColor' - encoding

folder='/PhotosX'
database = {}
for filename in listdir(folder):
path = folder + filename
gbr1 = cv2.imread(folder + filename)
wajah = HaarCascade.detectMultiScale(gbr1,1.1,4)
if len(wajah)>0:
x1, y1, width, height = wajah[0]
else:
x1, y1, width, height = 1, 1, 10, 10
x1, y1 = abs(x1), abs(y1)
x2, y2 = x1 + width, y1 + height
gbr = cv2.cvtColor(gbr1, cv2.COLOR_BGR2RGB)
gbr = Img.fromarray(gbr) # konversi dari OpenCV ke PIL
gbr_array = asarray(gbr)
face = gbr_array[y1:y2, x1:x2]
face = Img.fromarray(face)
face = face.resize((160,160))
face = asarray(face)
face = face.astype('float32')
mean, std = face.mean(), face.std()
face = (face - mean) / std
face = expand_dims(face, axis=0)
signature = MyFaceNet.predict(face)
cap = cv2.VideoCapture(0)
im = cap.read()
database[os.path.splitext(filename)[0]]=signature
That's the code above. I'm not sure why this isn't working for mw, i'm on windows. I've updated my drivers and the fil path is correct

Related

Why is the scatter Circle Color not resulting in a rainbow?

I am trying to follow this example from Matlab about coloring scatter points as a rainbow, while the x-position of the points is progressing towards the right side.
Here under "Vary Circle Color":
https://de.mathworks.com/help/matlab/ref/scatter.html
x = linspace(0,3*pi,200);
y = cos(x) + rand(1,200);
c = linspace(1,10,length(x));
scatter(x,y,[],c)
While c as a variable goes from 1 to 20 with 200 interpolations. I am trying to replicate this for my piece of code, but I keep getting random color and the x-axis isn't matching the rainbow distribution as this:
g = 6;
pt_x = [0, g, -g];
pt_y = [g, -g, -g];
sz = 10;
loop = 100;
% var(1, loop) = 0;
% c = linspace(-10,10,length(var));
% c = 1:loop;
c = -loop/2:1:loop/2 -1;
rand_x = randi([-g,g],1,1);
rand_y = randi([-g,g],1,1);
for i = 1:loop
r = randi([1,3],1,1);
x1 = (rand_x + pt_x(r)) / 2;
y1 = (rand_y + pt_y(r)) / 2;
seq_x(1, i) = x1;
seq_y(1, i) = y1;
rand_x = x1;
rand_y = y1;
end
scatter(seq_x, cos(seq_x),[],c, 'filled');
What am I missing here exactly? I would appreciate any help!
Expected to get a rainbow pattern
It resulted in a random pattern

Modifying bilinear interpolation matlab code to enlarge an image instead

I am trying to modify this code to enlarge an image instead of shrinking it by when I change the
eliminate the factor line and made shrinking factor= 2 and multiply by s where s is used, I didn't get the right output. Can anyone point me to what I am doing wrong.
Here is the code:
image=imread('b100.jpg');
factor=1.5;
shriking_factor= 1/factor;
[r c d] = size(image);
rn = floor(shriking_factor*r);
cn = floor(shriking_factor*c);
s = shriking_factor;
im_zoom = zeros(rn,cn,d);
for i = 1:rn;
x1 = cast(floor(i/s),'uint16');
x2 = cast(ceil(i/s),'uint32');
if x1 == 0
x1 = 1;
end
x = rem(i/s,1);
for j = 1:cn;
y1 = cast(floor(j/s),'uint32');
y2 = cast(ceil(j/s),'uint16');
if y1 == 0
y1 = 1;
end
ctl = image(x1,y1);
cbl = image(x2,y1);
ctr = image(x1,y2);
cbr = image(x2,y2);
y = rem(j/s,1);
tr = (ctr*y)+(ctl*(1-y));
br = (cbr*y)+(cbl*(1-y));
im_shrink(i,j) = (br*x)+(tr*(1-x));
end
end
image_shrink = cast(im_shrink,'uint8');
imshow(image_shrink)

Different intensity values for same image in OpenCV and MATLAB

I'm using Python 2.7 and OpenCV 3.x for my project for omr sheet evaluation using web camera.
While finding the number of white pixels in around the center of circle,I came to know that the intensity values are wrong, but it shows the correct values in MATLAB when I'm using imtool('a1.png').
I'm using .png image (datatype uint8).
just run the code and in the image go to [360:370,162:172] coordinate and see the intensity values.. it should not be 0.
find the images here -> a1.png a2.png
Why is this happening?
import numpy as np
import cv2
from matplotlib import pyplot as plt
#select radius of circle
radius = 10;
#function for finding white pixels
def thresh_circle(img,ptx,pty):
centerX = ptx;
centerY = pty;
cntOfWhite = 0;
for i in range((centerX - radius),(centerX + radius)):
for j in range((centerY - radius), (centerY + radius)):
if(j < img.shape[0] and i < img.shape[1]):
val = img[i][j]
if (val == 255):
cntOfWhite = cntOfWhite + 1;
return cntOfWhite
MIN_MATCH_COUNT = 10
img1 = cv2.imread('a1.png',0) # queryImage
img2 = cv2.imread('a2.png',0) # trainImage
sift = cv2.SIFT()# Initiate SIFT detector
kp1, des1 = sift.detectAndCompute(img1,None)# find the keypoints and descriptors with SIFT
kp2, des2 = sift.detectAndCompute(img2,None)
FLANN_INDEX_KDTREE = 0
index_params = dict(algorithm = FLANN_INDEX_KDTREE, trees = 5)
search_params = dict(checks = 50)
flann = cv2.FlannBasedMatcher(index_params, search_params)
matches = flann.knnMatch(des1,des2,k=2)
good = []# store all the good matches as per Lowe's ratio test.
for m,n in matches:
if m.distance < 0.7*n.distance:
good.append(m)
if len(good)>MIN_MATCH_COUNT:
src_pts = np.float32([ kp1[m.queryIdx].pt for m in good ]).reshape(-1,1,2)
dst_pts = np.float32([ kp2[m.trainIdx].pt for m in good ]).reshape(-1,1,2)
M, mask = cv2.findHomography(src_pts, dst_pts, cv2.LMEDS,5.0)
#print M
matchesMask = mask.ravel().tolist()
h,w = img1.shape
else:
print "Not enough matches are found - %d/%d" % (len(good),MIN_MATCH_COUNT)
matchesMask = None
img3 = cv2.warpPerspective(img1, M, (img2.shape[1],img2.shape[0]))
blur = cv2.GaussianBlur(img3,(5,5),0)
ret3,th3 = cv2.threshold(blur,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)
ret,th2 = cv2.threshold(blur,ret3,255,cv2.THRESH_BINARY_INV)
print th2[360:370,162:172]#print a block of image
plt.imshow(th2, 'gray'),plt.show()
cv2.waitKey(0)
cv2.imwrite('th2.png',th2)
ptyc = np.array([170,200,230,260]);#y coordinates of circle center
ptxc = np.array([110,145,180,215,335,370,405,440])#x coordinates of circle center
pts_src = np.zeros(shape = (32,2),dtype=np.int);#x,y coordinates of circle center
ct = 0;
for i in range(0,4):
for j in range(0,8):
pts_src[ct][1] = ptyc[i];
pts_src[ct][0] = ptxc[j];
ct = ct+1;
boolval = np.zeros(shape=(8,4),dtype=np.bool)
ct = 0;
for j in range(0,8):
for i in range(0,4):
a1 = thresh_circle(th2,pts_src[ct][0],pts_src[ct][1])
ct = ct+1;
if(a1 > 50):
boolval[j][i] = 1
else:
boolval[j][i] = 0

Get coordinate of new rectangle with Matlab's imrect

For my project, I have a lot of pictures that I need to extract a ROI. When my project starts, I want a picture to show and then the user to select the ROI that he/she wants. The function imrect seems to be doing that. I am trying to get the coordinate of the rectangle, once it has been dragged or resized. The problem is that the values returned do not seem to be correct.
I can't seem to find the problem and the related questions didn't help. I tried using imcrop, but couldn't do any better...
function [ new_image ] = getRoi(image)
rect = size(image);
rect = round(rect ./2);
figure, imshow(image);
h = imrect(gca, [5 5 rect(2) rect(1)]);
addNewPositionCallback(h,#(p) title(mat2str(p,3)));
fcn = makeConstrainToRectFcn('imrect',get(gca,'XLim'),get(gca,'YLim'));
accepted_pos = wait(h);
setPositionConstraintFcn(h,fcn);
%getPositionConstraintFcn(h);
pos = getPosition(h);
if round(pos(1)) < round(pos(2))
X1 = round(pos(1))
X2 = round(pos(2))
else
X1 = round(pos(2))
X2 = round(pos(1))
end
if round(pos(3)) < round(pos(4))
Y1 = round(pos(3))
Y2 = round(pos(4))
else
Y1 = round(pos(4))
Y2 = round(pos(3))
end
new_image = image(Y1:Y2, X1:X2);
%name = strcat('Roi_', datestr(clock, 'yyyymmddTHHMMSS'),'.png');
%prtIm(new_image, name, '-s');
new_image = image;
end
getPosition returns [xmin, ymin, width, height]. To get the coordinates you want, try
X1 = round(pos(1));
Y1 = round(pos(2));
X2 = round(X1 + pos(3));
Y2 = round(Y1 + pos(4));

How to show 40 gabor filter in matlab

can someone help me how to show gabor filter in matlab, i can show it but its not what i want. this is my code :
[Gf,gabout] = gaborfilter1(B,sx,sy,f,theta(j));
G{m,n,i,j} = Gf;
and this is gabor filter class:
function [Gf,gabout] = gaborfilter(I,Sx,Sy,f,theta);
if isa(I,'double')~=1
I = double(I);
end
for x = -fix(Sx):fix(Sx)
for y = -fix(Sy):fix(Sy)
xPrime = x * cos(theta) + y * sin(theta);
yPrime = y * cos(theta) - x * sin(theta);
Gf(fix(Sx)+x+1,fix(Sy)+y+1) = exp(-.5*((xPrime/Sx)^2+(yPrime/Sy)^2))*cos(2*pi*f*xPrime);
end
end
Imgabout = conv2(I,double(imag(Gf)),'same');
Regabout = conv2(I,double(real(Gf)),'same');
gabout = sqrt(Imgabout.*Imgabout + Regabout.*Regabout);
Then, I imshow with this code:
imshow(G{m,n,i,j},[]);
and the results :
But i want this result, can someone help me how to slove this?
Use the following function. I hope this is useful.
----------------------------------------------------------------
gfs = GaborFilter(51,0.45,0.05,6,4);
n=0;
for s=1:6
for d=1:4
n=n+1;
subplot(6,4,n)
imshow(real(squeeze(gfs(s,d,:,:))),[])
end
end
Sample Image
----------------------------------------------------------------
function gfs = GaborFilter(winLen,uh,ul,S,D)
% gfs(SCALE, DIRECTION, :, :)
winLen = winLen + mod(winLen, 2) -1;
x0 = (winLen + 1)/2;
y0 = x0;
if S==1
a = 1;
su = uh/sqrt(log(4));
sv = su;
else
a = (uh/ul)^(1/(S-1));
su = (a-1)*uh/((a+1)*sqrt(log(4)));
if D==1
tang = 1;
else
tang = tan(pi/(2*D));
end
sv = tang * (uh - log(4)*su^2/uh)/sqrt(log(4) - (log(4)*su/uh)^2);
end
sx = 1/(2*pi*su);
sy = 1/(2*pi*sv);
coef = 1/(2*pi*sx*sy);
gfs = zeros(S, D, winLen, winLen);
for d = 1:D
theta = (d-1)*pi/D;
for s = 1:S
scale = a^(-(s-1));
gab = zeros(winLen);
for x = 1:winLen
for y = 1:winLen
X = scale * ((x-x0)*cos(theta) + (y-y0)*sin(theta));
Y = scale * (-(x-x0)*sin(theta) + (y-y0)*cos(theta));
gab(x, y) = -0.5 * ( (X/sx).^2 + (Y/sy).^2 ) + (2*pi*1j*uh)*X ;
end
end
gfs(s, d, :, :) = scale * coef * exp(gab);
end
end
Replace the "cos" component by complex part->complex(0, (2*pi*f*xprime)) ans also multiply equation by scaling factor of (1/sqrt(2*Sy*Sx)).