AttributeError: set_red, while trying to change color values - colors

While trying to set up a image filter I've been running into a issue with applying those values to the pixels. I'm new to python, so it's probably a rather simply answer I'm assuming I'm missing something here with global versus local variables but I just don't know what.
def custom_filter(pixel_data):
if coin_flip() == 1:
new_red = int((pixel_data[0]) * .75)
else:
new_red = int((pixel_data[0]) * 1.25)
if coin_flip() == 1:
new_green = int((pixel_data[1]) * .75)
else:
new_green = int((pixel_data[1]) * 1.25)
if coin_flip() == 1:
new_blue = int((pixel_data[2]) * .75)
else:
new_blue = int((pixel_data[2]) * 1.25)
print(new_red, new_green, new_blue)
def change_image():
global image
for x in range(image.get_width()):
for y in range(image.get_height()):
pixel = image.get_pixel(x,y)
image = custom_filter(pixel)
image.set_red(x,y, image[0])
image.set_green(x,y, image[1])
image.set_blue(x,y, image[2])

Related

How do i make these two code snippets run in parallel

I would like to run these two parts of the code in parallel. Is this possible in python? How would i have to modify the code to accommodate this?
def smo(self, X, y):
iterations = 0
n_samples = X.shape[0]
# Initial coefficients
alpha = numpy.zeros(n_samples)
# Initial gradient
g = numpy.ones(n_samples)
while True:
yg = g * y
# KKT Conditions
y_pos_ind = (y == 1)
y_neg_ind = (numpy.ones(n_samples) - y_pos_ind).astype(bool)
alpha_pos_ind = (alpha >= self.C)
alpha_neg_ind = (alpha <= 0)
indices_violating_Bi_1 = y_pos_ind * alpha_pos_ind
indices_violating_Bi_2 = y_neg_ind * alpha_neg_ind
indices_violating_Bi = indices_violating_Bi_1 + indices_violating_Bi_2
yg_i = yg.copy()
yg_i[indices_violating_Bi] = float('-inf')
# First of the maximum violating pair
i = numpy.argmax(yg_i)
Kik = self.kernel_matrix(X, i)
indices_violating_Ai_1 = y_pos_ind * alpha_neg_ind
indices_violating_Ai_2 = y_neg_ind * alpha_pos_ind
indices_violating_Ai = indices_violating_Ai_1 + indices_violating_Ai_2
yg_j = yg.copy()
yg_j[indices_violating_Ai] = float('+inf')
# Second of the maximum violating pair
j = numpy.argmin(yg_j)
Kjk = self.kernel_matrix(X, j)
# Optimality criterion
if(yg_i[i] - yg_j[j]) < self.tol or (iterations >= self.max_iter):
break
min_term_1 = (y[i] == 1) * self.C - y[i] * alpha[i]
min_term_2 = y[j] * alpha[j] + (y[j] == -1) * self.C
min_term_3 = (yg_i[i] - yg_j[j]) / (Kik[i] + Kjk[j] - 2 * Kik[j])
# Direction search
lamda = numpy.min([min_term_1, min_term_2, min_term_3])
# Gradient update
g += lamda * y * (Kjk - Kik)
# Update coefficients
alpha[i] = alpha[i] + y[i] * lamda
alpha[j] = alpha[j] - y[j] * lamda
iterations += 1
print('{} iterations to arrive at the minimum'.format(iterations))
return alpha
I would like to run this line
Kik = self.kernel_matrix(X, i)
and this line
Kjk = self.kernel_matrix(X, j)
in parallel. How do i change the code to accommodate this?
Giving you a response with just the finished multi threading code probably wouldn't be that helpful to you and is hard given I don't know what the functions themselves do but check out this link: https://realpython.com/intro-to-python-threading/
The general idea is you will have to start a thread for each task you want to run in parallel like this:
thread1 = threading.Thread(target=kernel_matrix,args=(X,j))
thread1.start()
If you want to wait for a thread to finish you call thread.join()
You'll need to watch out for race conditions too good thread on that here: What is a race condition?

AttributeError: 'NoneType' object has no attribute 'magnitude'

class Force:
def __init__(self,magnitude,angle):
self.magnitude = magnitude
self.angle = angle
def get_horizontal(self):
return self.magnitude * cos(radians(self.angle))
def get_vertical(self):
return self.magnitude * sin(radians(self.angle))
def get_angle(self,use_degrees = True):
if use_degrees:
return self.angle
else:
return radians(self.angle)
def find_net_force(forces):
tot_hor = 0
tot_ver = 0
for i in forces:
tot_hor += i.get_horizontal()
tot_ver += i.get_vertical()
magnitude = (tot_hor ** 2 + tot_ver ** 2) ** 0.5
magnitude = round(magnitude,1)
angle = degrees(atan2((tot_ver),(tot_hor)))
angle = round(angle,1)
force_1 = Force(50, 90)
force_2 = Force(75, -90)
force_3 = Force(100, 0)
forces = [force_1, force_2, force_3]
net_force = find_net_force(forces)
print(net_force.magnitude)
print(nIt_force.get_angle())
When i execute this code i get,
print(net_force.magnitude)
AttributeError: 'NoneType' object has no attribute 'magnitude'
Where to look for the error, as I can see that something is related to the magnitude part.
It's at the bottom:
print(net_force.magnitude)
the_force is null because of find_net_force's return value.
The exception you saw should've had a stack trace showing you the line number.

Python :IndexError: list index out of range How to solve this error?

I am using bilateral filter for my work. I am getting following error:
src = cv2.imread(str(sys.argv[1]), 0) IndexError: list index out of
range
code:Bilateral bilter
import numpy as np
import cv2
import sys
import math
def distance(x, y, i, j):
return np.sqrt((x-i)**2 + (y-j)**2)
def gaussian(x, sigma):
return (1.0 / (2 * math.pi * (sigma ** 2))) * math.exp(- (x ** 2) / (2 * sigma ** 2))
def apply_bilateral_filter(source, filtered_image, x, y, diameter, sigma_i, sigma_s):
hl = diameter/2
i_filtered = 0
Wp = 0
i = 0
while i < diameter:
j = 0
while j < diameter:
neighbour_x = x - (hl - i)
neighbour_y = y - (hl - j)
if neighbour_x >= len(source):
neighbour_x -= len(source)
if neighbour_y >= len(source[0]):
neighbour_y -= len(source[0])
gi = gaussian(source[neighbour_x][neighbour_y] - source[x][y], sigma_i)
gs = gaussian(distance(neighbour_x, neighbour_y, x, y), sigma_s)
w = gi * gs
i_filtered += source[neighbour_x][neighbour_y] * w
Wp += w
j += 1
i += 1
i_filtered = i_filtered / Wp
filtered_image[x][y] = int(round(i_filtered))
def bilateral_filter_own(source, filter_diameter, sigma_i, sigma_s):
filtered_image = np.zeros(source.shape)
i = 0
while i < len(source):
j = 0
while j < len(source[0]):
apply_bilateral_filter(source, filtered_image, i, j, filter_diameter, sigma_i, sigma_s)
j += 1
i += 1
return filtered_image
if __name__ == "__main__":
src = cv2.imread(str(sys.argv[1]), 0)
filtered_image_OpenCV = cv2.bilateralFilter(src, 5, 12.0, 16.0)
cv2.imwrite("original_image_grayscale.png", src)
cv2.imwrite("filtered_image_OpenCV.png", filtered_image_OpenCV)
filtered_image_own = bilateral_filter_own(src, 5, 12.0, 16.0)
cv2.imwrite("filtered_image_own.png", filtered_image_own)
sys.argv[1] is indexing into the first element of the command line arguments list. If you're not providing an argument when running the program, e.g. python yourfilename.py testing, an IndexError will be thrown. Note that the 0th element of the list is the filename of the script.
Debug with print(sys.argv) immediately below if __name__ == "__main__": to view the contents of your sys.argv list.
Also, note that arguments are passed as strings, so the str() cast is superfluous.
It seems that something is not as you expect, this IndexError: list index out of range indicates that your list src = cv2.imread(str(sys.argv[1]), 0) doesn't have 2 elements in it, and only 1 exists.
Try debug your code:
if __name__ == "__main__":
print('This is the type of my sys.argv', type(sys.argv))
print('This is str(sys.argv) as full list --> ', str(sys.argv)) # my guess is that it will give only 1 item in the list, maybe you first need to do some splitting or etc, but the end result will be seen from you'r debugging :)
print('This is str(sys.argv[0]) first itme from list --> ', str(sys.argv[0]))
# add break point here
src = cv2.imread(str(sys.argv[1]), 0)
filtered_image_OpenCV = cv2.bilateralFilter(src, 5, 12.0, 16.0)
cv2.imwrite("original_image_grayscale.png", src)
cv2.imwrite("filtered_image_OpenCV.png", filtered_image_OpenCV)
filtered_image_own = bilateral_filter_own(src, 5, 12.0, 16.0)
cv2.imwrite("filtered_image_own.png", filtered_image_own)

select with bokeh not really working

I am using bokeh 0.12.2. I have a select with words. When i choose a word it should circle the dot data. It seems to work then stop. I am trying with 2 words, word1 and word2. lastidx is full of index.xc and yx are the location of the circle here is the code. This is working with one but not really if i change the value in the select:
for j in range(0,2):
for i in range(0,len(lastidx[j])):
xc.append(tsne_kmeans[lastidx[j][i], 0])
yc.append(tsne_kmeans[lastidx[j][i], 1])
source = ColumnDataSource(data=dict(x=xc, y=yc, s=mstwrd))
def callback(source=source):
dat = source.get('data')
x, y, s = dat['x'], dat['y'], dat['s']
val = cb_obj.get('value')
if val == 'word1':
for i in range(0,75):
x[i] = x[i]
y[i] = y[i]
elif val == 'word2':
for i in range(76,173):
x[i-76] = x[i]
y[i-76] = y[i]
source.trigger('change')
slct = Select(title="Word:", value="word1", options=mstwrd , callback=CustomJS.from_py_func(callback))
# create the circle around the data where the word exist
r = plot_kmeans.circle('x','y', source=source)
glyph = r.glyph
glyph.size = 15
glyph.fill_alpha = 0.0
glyph.line_color = "black"
glyph.line_dash = [4, 2]
glyph.line_width = 1
x and y are loaded with all the data here and I just pick the data for the word I select. It seems to work and then it does not.
Is it possible to do that as a stand alone chart?
Thank you
I figured it out: code here is just to see if this was working. This will be improved of course. And may be this is what was written here at the end:
https://github.com/bokeh/bokeh/issues/2618
for i in range(0,len(lastidx[0])):
xc.append(tsne_kmeans[lastidx[0][i], 0])
yc.append(tsne_kmeans[lastidx[0][i], 1])
addto = len(lastidx[1])-len(lastidx[0])
# here i max out the data which has the least
# so when you go from one option to the other it
# removes all the previous data circle
for i in range(0,addto):
xc.append(-16) # just send them somewhere
yc.append(16)
for i in range(0, len(lastidx[1])):
xf.append(tsne_kmeans[lastidx[1][i], 0])
yf.append(tsne_kmeans[lastidx[1][i], 1])
x = xc
y = yc
source = ColumnDataSource(data=dict(x=x, y=y,xc=xc,yc=yc,xf=xf,yf=yf))
val = "word1"
def callback(source=source):
dat = source.get('data')
x, y,xc,yc,xf,yf = dat['x'], dat['y'], dat['xc'], dat['yc'], dat['xf'], dat['yf']
# if slct.options['value'] == 'growth':
val = cb_obj.get('value')
if val == 'word1':
for i in range(0,len(xc)):
x[i] = xc[i]
y[i] = yc[i]
elif val == 'word2':
for i in range(0,len(xf)):
x[i] = xf[i]
y[i] = yf[i]
source.trigger('change')
slct = Select(title="Most Used Word:", value=val, options=mstwrd , callback=CustomJS.from_py_func(callback))
# create the circle around the data where the word exist
r = plot_kmeans.circle('x','y', source=source)
I will check if i can pass a matrix. Don't forget to have the same size of data if not you will have multiple options circled in the same time.
Thank you

Use str to set attribute for module in python

I'm trying to learn python (using python3.2), and right now I'm creating a program designed to scale images:
from PIL import Image
def newSizeChoice():
scale = input('Please enter the scale to be applied to the image: x')
while float(scale) <= 0:
scale = input('Invalid: scale must be positive. Please enter a new scale: x')
return float(scale)
def bestFilter(x):
if x < 1:
filter = 'ANTIALIAS'
elif x == 2:
filter = 'BILINEAR'
elif x == 4:
filter = 'BICUBIC'
else:
filter = 'NEAREST'
return filter
def resize(img, width, height, scale, filter):
width = width * scale
height = height * scale
newimg = img.resize((width, height), Image.filter)
newimg.save('images\\LargeCy.png')
newimg.show()
img = Image.open('images\\cy.png')
pix = img.load()
width, height = img.size
scale = float(newSizeChoice())
filter = bestFilter(scale)
resize(img, width, height, scale, filter)
It's a little bit of a mess right now, because I'm still working on it, but my problem is that when I set the filter in function 'bestFilter', I'm not able to use it to set the filter in function 'resize'. The error I keep getting:
Traceback (most recent call last):
File "C:\Users\14davidson_a\Desktop\Projects\Exercises\ImageScaling.py", line 33, in <module>
resize(img, width, height, scale, filter)
File "C:\Users\14davidson_a\Desktop\Projects\Exercises\ImageScaling.py", line 23, in resize
newimg = img.resize((width, height), Image.filter)
AttributeError: 'module' object has no attribute 'filter'
Question: Is there a way I can use a string to set the attribute for a module?
You are trying to use Image.filter, which is not defined on the Image module. Perhaps you meant to use the filter argument of the method instead?
def resize(img, width, height, scale, filter):
width = width * scale
height = height * scale
newimg = img.resize((width, height), filter)
newimg.save('images\\LargeCy.png')
newimg.show()
You don't use the filter argument for anything else in that method.
You'll need to update your bestFilter() function to return a valid Image filter:
def bestFilter(x):
if x < 1:
filter = Image.ANTIALIAS
elif x == 2:
filter = Image.BILINEAR
elif x == 4:
filter = Image.BICUBIC
else:
filter = Image.NEAREST
return filter
You could simplify that function by using a mapping:
_scale_to_filter = {
1: Image.ANTIALIAS,
2: Image.BILINEAR,
4: Image.BICUBIC,
}
def bestFilter(x):
return _scale_to_filter.get(x, Image.NEAREST)

Resources