Is there a way to fix value-error problem - python

Hello guys i am trying to implement an algortihm to remove water from underwater images and make image more noticable , but i got an errror ValueError: max() arg is an empty sequence , at the function homomorpic on this line r = max(np.ravel(result[:,:i])) , the error is caused because the result array is empty but i filled it above .Here the code below.
import numpy as np
import cv2
def homomorpic(img):
img = np.float32(img)
#img = img/255
rows , cols , dim = img.shape
(rh,rl,cutoff) = 1.3, 0.8, 32
b,g,r = cv2.split(img)
y_log_b = np.log(b + 0.01)
y_log_g = np.log(g + 0.01)
y_log_r = np.log(r + 0.01)
y_fft_b= np.fft.fft2(y_log_b)
y_fft_g= np.fft.fft2(y_log_g)
y_fft_r= np.fft.fft2(y_log_r)
y_fft_b_shift = np.fft.fftshift(y_log_b)
y_fft_g_shift = np.fft.fftshift(y_log_g)
y_fft_r_shift = np.fft.fftshift(y_log_r)
D0=cols/cutoff
H= np.ones((rows,cols))
B= np.ones((rows,cols))
for i in range(rows):
for j in range(cols):
H[i][j] = ((rh-rl)* (1-np.exp(-((i-rows/2)**2+(j-cols/2)**2)/(2*D0**2))))+rl
result_filter_b = H* y_fft_b_shift
result_filter_g = H* y_fft_g_shift
result_filter_r = H* y_fft_r_shift
result_b_intern = np.real(np.fft.ifft2(np.fft.ifftshift(result_filter_b)))
result_g_intern = np.real(np.fft.ifft2(np.fft.ifftshift(result_filter_g)))
result_r_intern = np.real(np.fft.ifft2(np.fft.ifftshift(result_filter_r)))
result_b = np.exp(result_b_intern)
result_g = np.exp(result_g_intern)
result_r = np.exp(result_r_intern)
result = np.zeros((rows,cols,dim))
result[:,:,0] = result_b
result[:,:,1] = result_g
result[:,:,2] = result_r
ma = -1
mi = 500
for i in range(3):
r = max(np.ravel(result[:,:i]))
x = min(np.ravel(result[:,:i]))
if r > ma :
ma = r
if x < mi :
mi = x
return(result)
image = cv2.imread("eg.png")
image2 = homomorpic(image)
Thanks for any help or suggestion.

In this loop for i in range(3): the first value of i would be 0.
This will later on lead to this r = max(np.ravel(result[:,:0])) where the result from the slicing would be empty.
You would want to shift yourrange forward like this:
for i in range(1, 3+1):

Related

Really different matrixes in Python producing the same images

I am working on some RGB images processing. I suggest anyone who reads this to ignore the functions I've created before the main code (these are not relevant to the problem itself, I beleive).
The RGB1 image I am using is this one:
Here is my code so far:
import sys
import numpy as np
import quaternion
import matplotlib.pyplot as plt
from pandas import *
import scipy.io as spio
import matplotlib.image as img
# IGNORE UNTIL NEXT COMMENT #
np.set_printoptions(threshold=sys.maxsize)
def row_wise_fft(A):
A = np.asarray(A)
rowWiseFFT = np.zeros((A.shape[0], A.shape[1]), dtype='complex')
for i in range(0, A.shape[0]):
rowWiseFFT[i, :] = np.fft.fft(A[i, :])
return rowWiseFFT
def row_wise_ifft(A):
A = np.asarray(A)
rowWiseFFT = np.zeros(A.shape, dtype='complex')
for i in range(0, A.shape[0]):
rowWiseFFT[i, :] = np.fft.ifft(A[i, :])
return rowWiseFFT
def split_parts(A):
return [A.real, A.imag]
def column_wise_fft(A):
A = np.asarray(A)
columnWiseFFT = np.zeros((A.shape[0], A.shape[1]), dtype='complex')
for i in range(0, A.shape[1]):
columnWiseFFT[:, i] = np.fft.fft(A[:, i])
return columnWiseFFT
def final_dqft(FuvR, FuvI):
[FuvR, FuvI] = [np.asarray(FuvR), np.asanyarray(FuvI)]
[FuvRReal, FuvRImag] = split_parts(FuvR)
[FuvIReal, FuvIImag] = split_parts(FuvI)
FuvQ = [[None]*FuvR.shape[1]]*FuvR.shape[0]
FuvQ = np.asarray(FuvQ)
for i in range(0, FuvQ.shape[0]):
for k in range(0, FuvQ.shape[1]):
FuvQ[i][k] = np.quaternion(
FuvRReal[i][k], FuvIReal[i][k], FuvRImag[i][k], FuvIImag[i][k])
return FuvQ
def column_wise_ifftshift(A):
columnWiseIfftshift = np.zeros((A.shape[0], A.shape[1]), dtype='complex')
for i in range(0, A.shape[1]):
columnWiseIfftshift[:, i] = np.fft.ifftshift(A[:, i])
return columnWiseIfftshift
def column_wise_fftshift(A):
columnWisefftshift = np.zeros(A.shape, dtype='complex')
for i in range(0, A.shape[1]):
columnWisefftshift[:, i] = np.fft.fftshift(A[:, i])
return columnWisefftshift
def row_wise_ifftshift(A):
rowWiseIfftshift = np.zeros((A.shape[0], A.shape[1]), dtype='complex')
for i in range(0, len(A)):
rowWiseIfftshift[i] = np.fft.ifftshift(A[i])
return rowWiseIfftshift
def row_wise_fftshift(A):
rowWisefftshift = np.zeros((A.shape[0], A.shape[1]), dtype='complex')
for i in range(0, len(A)):
rowWisefftshift[i] = np.fft.fftshift(A[i])
return rowWisefftshift
def full_DQFT_calculator(A):
fun = row_wise_fftshift(row_wise_fft(row_wise_ifftshift(A)))
[funReal, funImag] = split_parts(fun)
FuvR = column_wise_fftshift(
column_wise_fft(column_wise_ifftshift(funReal)))
FuvI = column_wise_fftshift(
column_wise_fft(column_wise_ifftshift(funImag)))
FuvQ = final_dqft(FuvR, FuvI)
return FuvQ
# STOP IGNORING FROM NOW ON #
image = img.imread("RGB1.jpg")
# Keep the Red,Green and Blue Channels.
R = np.asarray(image[:, :, 0])
G = np.asarray(image[:, :, 1])
B = np.asarray(image[:, :, 2])
# Defining h_r = 0 ; h_i = Red ; h_j = Green ; h_k = Blue
(h_r, h_i, h_j, h_k) = (np.zeros(R.shape), R, G, B)
# Some intermediatte calculations
firstIntegral = full_DQFT_calculator(h_i)
secondIntegral = full_DQFT_calculator(h_j)
thirdIntegral = full_DQFT_calculator(h_k)
final_result = np.empty(firstIntegral.shape, dtype='quaternion')
for i in range(0, final_result.shape[0]):
for j in range(0, final_result.shape[1]):
final_result[i][j] = np.quaternion(-firstIntegral[i][j].x-secondIntegral[i][j].y+thirdIntegral[i][j].z, firstIntegral[i][j].w - secondIntegral[i][j].z - thirdIntegral[i]
[j].y, secondIntegral[i][j].w - thirdIntegral[i][j].x - firstIntegral[i][j].z, firstIntegral[i][j].y + secondIntegral[i][j].x + thirdIntegral[i][j].w)
real_final_result = np.empty(final_result.shape, dtype='float')
for i in range(0, real_final_result.shape[0]):
for j in range(0, real_final_result.shape[1]):
real_final_result[i][j] = final_result[i][j].w
print('Parte real da primeira linha da matriz (transformada quaterniĆ³nica): \n',real_final_result[0], '\n')
i_final_result = np.empty(final_result.shape, dtype='float')
for i in range(0, i_final_result.shape[0]):
for j in range(0, i_final_result.shape[1]):
i_final_result[i][j] = final_result[i][j].x
print('Componente i da primeira linha da matriz (transformada quaterniĆ³nica): \n',i_final_result[0], '\n')
print(real_final_result[0] - i_final_result[0])
The difference between the two matrixes (i.e., the last print) is huge but when I try to print the matrixes using the following code:
fig = plt.figure()
plt.set_cmap('gray')
ax1 = fig.add_subplot(121)
plt.imshow(real_final_result)
plt.clim([0,1])
ax1.title.set_text('Re(TFQ)')
ax2 = fig.add_subplot(122)
plt.imshow(i_final_result)
plt.clim([0, 1])
ax2.title.set_text('I(TFQ)')
plt.show()
I obtain the exact same image. Can someone tell why is this happening?

Python function calling with variable vs raw numbers

I am trying to implement a pso algorithm from Wikipedia https://en.wikipedia.org/wiki/Particle_swarm_optimization.
My problem is that when I am calling the cost function with a variable (Gbest), and then manually calling the cost function (with the Gbest data) I get a different output (cost) like the image bellow:
Code fault
I am new to python so thank you for any suggestions.
Here is the complete code:
import matplotlib.pyplot as plt
import numpy as np
from control.matlab import *
A = np.array([[0,0,1],[0,1,0],[1,2,-2]])
B = np.array( [[0],[1],[0]])
C = np.array([[0, 1,0]])
D = np.zeros([C.shape[0],B.shape[1]])
sys = ss(A,B,C,D)
sys_tf = tf(sys)
s = tf('s')
def cost(kp,ki):
global sys_tf, G, y, t, r
G = kp + ki/s
C = feedback(sys_tf*G, 1)
y, t = step(C, linspace(0,100))
r = np.ones(len(t))
return np.sum(y-r)**2
part = 100
ite = 10000
dim = 2
w = 0.001
wdamp = 0.99
phip = 0.9
phig = 0.1
blo, bup = -10,10
x = np.zeros([dim, part])
v = np.zeros([dim, part])
pbest = np.zeros([dim, part])
gbest = np.array([1000000,1000000])
for i in range(part):
for k in range(dim):
x[k][i] = pbest[k][i] = np.random.uniform(blo, bup)
v[k][i] = np.random.uniform(-np.abs(bup - blo), np.abs(bup - blo))
if cost(pbest[0][i], pbest[1][i]) < cost(gbest[0], gbest[1]):
gbest = np.array([pbest[0][i], pbest[1][i]])
for it in range(ite):
for i in range(part):
for k in range(dim):
rp = np.random.uniform(0,1)
rg = np.random.uniform(0,1)
v[k,:] = w*v[k,:] + phip*rp*(pbest[k,:] - x[k,:]) + phig*rg*(gbest[k] - x[k,:])
x[k,:] = x[k,:] + v[k,:]
w = w*wdamp
if cost(x[0][i], x[1][i]) < cost(pbest[0][i], pbest[1][i]):
pbest[:,i] = x[:,i]
if cost(pbest[0][i], pbest[1][i]) < cost(gbest[0], gbest[1]):
gbest = np.array([pbest[0][i], pbest[1][i]])
plt.plot(t, y, 'ro')
plt.plot(t, r, 'x')
plt.pause(0.005)
plt.title(gbest)
print([gbest, cost(gbest[0], gbest[1])])

Why I got ModuleNotFoundError when I try to run the import statement?

I'm trying to import these on Jupyter, however I got an error when I run these code that say ModuleNotFoundError: No module named 'anna_phog'. I have another python file named as 'anna_phog'. How do I fix this?
below is 'anna_phog_demo.py' where I got the error
from anna_phog import anna_phog
import imageio
import matplotlib.pyplot as plt
image_path = "image_0058.jpg"
S = 8
angle = 360
Level = 3
roi = [1,225,1,300]
save=True
Image = imageio.imread(image_path)
p = anna_phog(Image, bin, angle, Level, roi)
print("P: \n{}".format(p))
print(len(p), type(p))
And below is the 'anna_phog.py' code
import numpy as np
import imageio
import cv2
import matplotlib.pyplot as plt
def anna_phog(Img, bin, angle, L, roi):
if Img.shape[2] == 3:
G = cv2.cvtColor(Img, cv2.COLOR_BGR2GRAY)
else:
G = Img
if np.sum(G) > 100:
# apply automatic Canny edge detection using the computed median
sigma = 0.33
v = np.median(G)
lower = int(max(0, (1.0 - sigma) * v))
upper = int(min(255, (1.0 + sigma) * v))
E = cv2.Canny(G,lower,upper) #high and low treshold
GradientX, GradientY = np.gradient(G)
GradientYY = np.gradient(GradientY, axis=1)
Gr = np.sqrt(np.square(GradientX)+np.square(GradientY))
index = GradientX == 0
GradientX[index] = 1e-5 #maybe another value
YX = GradientY*GradientX
if angle == 180: A = ((np.arctan(YX)+(np.pi/2))*180)/np.pi
if angle == 360: A = ((np.arctan2(GradientY,GradientX)+np.pi)*180)/np.pi
bh, bv = anna_BinMatrix(A,E,Gr,angle,bin)
else:
bh = np.zeros(Img.shape)
bv = np.zeros(Img.shape)
bh_roi = bh[roi[0]:roi[1], roi[2]:roi[3]]
bv_roi = bv[roi[0]:roi[1], roi[2]:roi[3]]
p = anna_PhogDescriptor(bh_roi,bv_roi,L,bin)
return p
def anna_BinMatrix(A,E,G,angle,bin):
n, contorns = cv2.connectedComponents(E, connectivity=8)
X = E.shape[1]
Y = E.shape[0]
bm = np.zeros(shape=(Y,X))
bv = np.zeros(shape=(Y,X))
nAngle = angle/bin
for i in range(n):
posY, posX = np.where(contorns==i)
for j in range(posY.shape[0]):
pos_x = posX[j]
pos_y = posY[j]
b = np.ceil(A[pos_y,pos_x]/nAngle)
if b==0: bin=1
if G[pos_y,pos_x]>0:
bm[pos_y,pos_x] = b
bv[pos_y,pos_x] = G[pos_y,pos_x]
return (bm, bv)
def anna_PhogDescriptor(bh,bv,L,bin):
p = np.array([])
#level 0
for b in range(bin):
ind = bh==b
p = np.append(p, np.sum(bv[ind]))
#higher levels
for l in range(1, L+1):
x = int(np.trunc(bh.shape[1]/(2**l)))
y = int(np.trunc(bh.shape[0]/(2**l)))
for xx in range(0, bh.shape[1]-x+1, x):
for yy in range(0, bh.shape[0]-y+1, y):
print(l)
bh_cella = bh[yy:yy+y, xx:xx+x]
bv_cella = bv[yy:yy+y, xx:xx+x]
for b in range(bin):
ind = bh_cella==b
p = np.append(p, np.sum(bv_cella[ind], axis=0))
if np.sum(p)!=0:
p = p/np.sum(p)
return p
Below is the screenshot of the folder where I put these file
folder path

MPC with python and Error ValueError: `f0` passed has more than 1 dimension

I wrote a MPC with Python and it worked before. After a long time I want to use it again but I got this Error
f0 passed has more than 1 dimension.
But I didn't change anything on my code. It is some kind of strange.
Here is my code:
import numpy as np
import numpy.linalg as npl
import matplotlib.pyplot as plt
from scipy.optimize import minimize
def mpcAugment(Am, Bm, Cm ):
"Function for Augmented Model"
nx, nu = Bm.shape
ny = Cm.shape[0]
A = np.zeros((nx+ny,nx+ny))
A[0:nx,0:nx] = Am
A[nx:nx+ny,0:nx] = Cm#Am
A[nx:nx+ny,nx:nx+ny] = np.eye(ny)
B = np.zeros((nx+ny,nu))
B[0:nx,:nu] = Bm
B[nx:nx+ny,:nu] = Cm#Bm
C = np.zeros((ny,nx+ny))
C[:ny,nx:nx+ny] = np.eye(ny)
return A, B, C
'Define Parameters'
k = 0.4
AICB = 153.8
mcp = 8.8e4
vamb1 = 30
vamb2 = 45
a = -k*AICB/mcp
b = -1/mcp
Ts = 20
VICBref = -5.0
Am = np.array([[1+Ts*a]])
Bm = np.array([[Ts*b]])
Gm = np.array([[-Ts*a]])
Cm = np.array([[1]])
A, B, C = mpcAugment(Am,Bm,Cm)
A, G, C = mpcAugment(Am,Gm,Cm)
nx, nu = B.shape
ny = C.shape[0]
nd = G.shape[1]
Np = 20
Nu = 5
F = np.zeros((Np*ny,nx))
PHI = np.zeros((Np*ny,Nu*nu))
PHIw = np.zeros((Np*ny,Np*nd))
for i in range(0,Np):
Ai = npl.matrix_power(A, i+1)
F[i*ny:(i+1)*ny,:] = C#Ai
for j in range(0, Nu):
if j <= i:
Aij = np.linalg.matrix_power(A, i-j)
PHI[i*ny:(i+1)*ny, j*nu:(j+1)*nu] = C#Aij#B
for j in range(0, Np):
if j <= i:
Aij = np.linalg.matrix_power(A, i-j)
PHIw[i*ny:(i+1)*ny, j*nd:(j+1)*nd] = C#Aij#G
umax = 3100
umin = 0
Q = np.eye(Np*ny)
R = 1e-2*np.eye(Nu*nu)
Rs = VICBref*np.ones((Np*ny,1))
Ainq = np.zeros((2*Nu*nu,Nu*nu))
binq = np.zeros((2*Nu*nu,1))
cinq = np.zeros((2*Nu*nu,1))
for i in range(0,Nu):
binq[i*nu:(i+1)*nu] = umax
binq[(i+Nu)*nu:(Nu+i+1)*nu] = 1
cinq[i*nu:(i+1)*nu] = 1
cinq[(i+Nu)*nu:(Nu+i+1)*nu] = -1
for j in range(0,i+1):
Ainq[i*nu:(i+1)*nu,j*nu:(j+1)*nu] = np.eye(nu)
Ainq[(i+Nu)*nu:(Nu+i+1)*nu,j*nu:(j+1)*nu] = np.eye(nu)
u0 = 0
def objective(du):
dU = np.array(du).reshape((len(du),1))
Y = F#x + PHI#dU + PHIw#w
return np.transpose((Rs-Y))#(Rs-Y)+np.transpose(dU)#R#(dU)
def constraint1(du):
dU = np.array(du).reshape((len(du),1))
return (binq - Ainq#dU - cinq*u0)[0]
#print(objective([1,1,1]))
ulim = (umin, umax)
bnds = np.kron(np.ones((Nu,1)),ulim)
#print(bnds)
Um = np.ones((nu*Nu,1))
Tsim = 5e4
time = np.arange(0,Tsim,Ts)
Nt = len(time)
xm = np.zeros((Nt,1))
um = np.zeros((Nt,nu))
ym = np.zeros((Nt,ny))
xm[0] = 0
ym[0] = Cm.dot(xm[0])
w = np.zeros((Np*nd,1))
print('Am = ',Am)
print('Bm = ',Bm)
print('Cm = ',Cm)
x = np.zeros((nx,1))
x[1] = xm[0]
vamb = vamb1
Vamb = np.zeros((Nt,1))
Ns = int(np.floor(Nt/2))
Vamb[0:Ns] = vamb1*np.ones((Ns,1))
Vamb[Ns:Nt] = vamb2*np.ones((Nt-Ns,1))
Vref = VICBref*np.ones((Nt,1))
con = {'type':'ineq','fun':constraint1}
for i in range(0,Nt-1):
sol = minimize(objective, Um, method = 'SLSQP',constraints = con)
if sol.success == False:
print('Error Cant solve problem')
exit()
Um = sol.x
um[i+1] = um[i] + Um[0]
u0 = um[i+1]
xm[i+1] = Am.dot(xm[i])+Bm.dot(um[i+1])+Gm.dot(Vamb[i])
ym[i+1] = Cm.dot(xm[i+1])
for j in range(0,Np):
if i+j < Nt:
Rs[j] = Vref[i+j]
w[j] = Vamb[i+j]-Vamb[i+j-1]
else:
Rs[j] = Vref[Nt-1]
w[j] = 0
x[0] = xm[i+1] - xm[i]
x[1] = xm[i+1]
print('Q = ',um[i+1],' , VICB = ',xm[i+1], ' vamb = ', Vamb[i])
hour = 60*60
plt.figure()
plt.subplot(2,1,1)
plt.plot(time/hour,ym)
plt.plot(time/hour,Vref,'--')
plt.xlabel('time(hours)')
plt.xlim([0, Tsim/hour])
plt.subplot(2,1,2)
plt.plot(time/hour,um)
plt.xlim([0, Tsim/hour])
plt.show()
It about a controller, which control the temperature of a cool box.
Is that possible that anything changed in main simply code?
I think the problem is now in minimizations part.
I reinstalled all of my libraries and it worked

How to square the individual matrix value using python?

Cost function implemented with Python:
**Thanks for help to achieve this.
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
load_data = pd.read_csv('C:\python_program\ex1data1.txt',sep = ",",header = None)
feature_vale = load_data[0]
y = np.matrix(load_data[1])
m = len(feature_vale)
plt.scatter(load_data[0],load_data[1],marker='+',c = 'r')
plt.title("Cost_Function")
plt.xlabel("Population of City in 10,000s")
plt.ylabel("Profit in $10,000s")
df = pd.DataFrame(pd.Series(1,index= range(0,m)))
df[1] = load_data[0]
X = np.matrix(df)
row_theta = np.zeros(2,dtype = int)
theta = np.array([row_theta]) # Transpose the array
prediction = np.dot(X,theta.T)
error = (prediction-y.T)
error_df = pd.DataFrame(error)
#square the error
squared_error = np.square(error_df)
sum = np.sum(squared_error)
print(sum)
J = np.sum(squared_error) / (2 * m)
print(J)
Data reference link: searchcode.com/codesearch/view/5404318
repeat the following steps and let me know
load_data = pd.read_csv('data.txt',sep = ",",header = None)
feature_vale = load_data[0]
y = np.matrix(load_data[1])
m = len(feature_vale)
#print(m)
#plt.scatter(load_data[0],load_data[1])
df = pd.DataFrame(pd.Series(1,index= range(0,m)))
df[1] = load_data[0]
X = np.matrix(df)
row_theta = np.zeros(2,dtype = int)
theta = np.array([row_theta]) # Transpose the array
print(theta.T)
prediction = np.matmul(X,theta.T)
error = (prediction-y)
error_df = pd.DataFrame(error)
squared_error = np.square(error_df)
print(squared_error)

Categories