Polyline() - change colour with an array value - wpf

I'm trying to create a very simple example of a for steps in [] loop using a Polyline() inside an IronPython WPF application. Each iteration of the loop should draw a different colour however Brushes implements a set of predefined System.Windows.Media.SolidColorBrush objects. I can't work out how to swap Red for my steps variable.
def polylineShape(self):
x = self.myCanvas.Width/2
y = self.myCanvas.Height/2
polyline = Polyline()
polyline.StrokeThickness = 5
for steps in ['Red','Blue','Green','Black']:
x = x
y = x
polyline.Points.Add(Point(x,y))
x = x + 40
polyline.Points.Add(Point(x,y))
polyline.Stroke = Brushes.Red #change colour on iteration
self.myCanvas.Children.Add(polyline)

I created a solution with some trial and error, I couldn't work out how to pass colours directly to the Brushes type.
def polylineShape(self):
x = 0
y = 0
for steps in [Brushes.SteelBlue, Brushes.DarkOrange, Brushes.DarkSeaGreen, Brushes.Honeydew]:
polyline = Polyline()
polyline.StrokeThickness = self.myCanvas.Height/4
x = 0
y = y + self.myCanvas.Height/4
polyline.Points.Add(Point(x,y))
x = self.myCanvas.Width
polyline.Points.Add(Point(x,y))
polyline.Stroke = steps
self.myCanvas.Children.Add(polyline)

Related

Interactive plot to change array values (MATLAB)

N = 500;
pattern = zeros(N,N);
grid on
plot(pattern)
% gets coordinates of modified cells
[x,y] = ginput;
% convert coordinates to integers
X = uint8(x);
Y = uint8(y);
% convert (X,Y) into linear indices
indx = sub2ind([N,N],x,y);
% switch desired cells on (value of 1)
pattern(indx) = 1;
I'm trying to assign several elements of a zeros array the value of 1. Basically I want to create an interactive plot where the user decides what cells he wants to turn on and then save his drawing as a matrix. In Python it's very simple to use the on_click with Matplotlib, but Matlab is weird and I can't find a clear answer. What's annoying is you can't see where you clicked until you save your changes and check the final matrix. You also can't erase a point if you made a mistake.
Moreover I get the following error : Error using sub2ind Out of range subscript. Error in createPattern (line 12) indx = sub2ind([N,N],X,Y);
Any idea how to fix it?
function CreatePattern
hFigure = figure;
hAxes = axes;
axis equal;
axis off;
hold on;
N = 3; % for line width
M = 20; % board size
squareEdgeSize = 5;
% create the board of patch objects
hPatchObjects = zeros(M,M);
for j = M:-1:1
for k = 1:M
hPatchObjects(M - j+ 1, k) = rectangle('Position', [k*squareEdgeSize,j*squareEdgeSize,squareEdgeSize,squareEdgeSize], 'FaceColor', [0 0 0],...
'EdgeColor', 'w', 'LineWidth', N, 'HitTest', 'on', 'ButtonDownFcn', {#OnPatchPressedCallback, M - j+ 1, k});
end
end
Board = zeros(M,M);
playerColours = [1 1 1; 0 0 0];
xlim([squareEdgeSize M*squareEdgeSize]);
ylim([squareEdgeSize M*squareEdgeSize]);
function OnPatchPressedCallback(hObject, eventdata, rowIndex, colIndex)
% change FaceColor to player colour
value = Board(rowIndex,colIndex);
if value == 1
set(hObject, 'FaceColor', playerColours(2, :));
Board(rowIndex,colIndex) = 0; % update board
else
set(hObject, 'FaceColor', playerColours(1, :));
Board(rowIndex,colIndex) = 1; % update board
end
end
end
I found this link and modified the code to be able to expand the board and also select cells that have been turned on already to switch them off.
Now I need a way to extract that board value to save the array.

How can i concatenate three 2D arrays which contain hue, saturation and intensity values in their respective arrays and display that as an image?

I am new to image processing and python. As you can see from my code, i managed to convert my RGB image to HSI by using the different formulas that i found.
I stored the values of hue, saturation and intensity in three different arrays. That is also in the code down below. How can i concatenate those three arrays and display the concatenated image as an image?
import math
from PIL import Image
img = Image.open("D:\\Texture analysis\\trees-clolorful-aerial-view-wallpaper.jpg")
rgb_img = img.convert('RGB')
row, col = img.size
print(row, col)
i = j = 0
satValue = 0
inValue = 0
hueValue = 0
squareValue = 0
hueArray = [[0 for x in range(row)] for y in range(col)]
satArray = [[0 for x in range(row)] for y in range(col)]
inArray = [[0 for x in range(row)] for y in range(col)]
division = 0
denominator = 0
numerator = 0
radAngle = 0
degAngle = 0
product = 0
sqr = 0
count = 0
uCount = 0
while i < row:
j = 0
while j < col:
red, green, blue = rgb_img.getpixel((i, j))
hRed = sRed = iRed = red
hGreen = sGreen = iGreen = green
hBlue = sBlue = iBlue = blue
# =========================Saturation Calculation==============================
if sRed == 0 and sGreen == 0 and sBlue == 0:
satValue = 0
satArray[i][j] = 0
else:
if (sRed < sGreen) and (sRed < sBlue):
satValue = 1 - (((3) * (sRed)) / (sRed + sGreen + sBlue))
satArray[i][j] = satValue
# print(satValue)
elif (sGreen < sRed) and (sGreen < sBlue):
satValue = 1 - (((3) * (sGreen)) / (sRed + sGreen + sBlue))
satArray[i][j] = satValue
# print(satValue)
else:
satValue = 1 - (((3) * (sBlue)) / (sRed + sGreen + sBlue))
satArray[i][j] = satValue
# print(satValue)
# =============================================================================
# ==========================Intensity Calculation==============================
inValue = (iRed + iGreen + iBlue) / 3
inArray[i][j] = inValue
count += 1
print(inValue, count)
# =============================================================================
# =============================Hue Calculation=================================
product = (hRed - hBlue) * (hGreen - hBlue)
sqr = (hRed - hGreen) * (hRed - hGreen)
denominator = math.sqrt(sqr + product)
if denominator != 0:
numerator = ((hRed - hGreen) + (hRed - hBlue)) / 2
division = numerator / denominator
radAngle = math.acos(division)
degAngle = math.degrees(radAngle)
if hBlue <= hGreen:
hueValue = degAngle
hueArray[i][j] = hueValue
elif hBlue > hGreen:
hueValue = 360 - degAngle
hueArray[i][j] = hueValue
elif denominator == 0:
hueValue = 0
hueArray[i][j] = hueValue
#print(hueValue, count)
# =============================================================================
j += 1
i += 1 print(i, j)
PS. You will be seeing a lot of my amateur code in the future as well :D
I can see what's going wrong now I am back at a computer. You probably tried this:
#!/usr/bin/env python3
from PIL import Image
img = Image.open('start.png')
hsvimg = img.convert('HSV')
hsvimg.save('result.png')
And if you do that, you actually get an error message:
OSError: cannot write mode HSV as PNG
because, PNG images are always in sRGB colourspace, so it correctly declines to write your HSV image. The thing is though, that the colourspace conversion actually worked and the values in the image actually are the HSV values that you want. You can check this with:
img.getpixel((X,Y))
and
hsvimg.getpixel((X,Y))
where X and Y are any random coordinates you like. You will see the the latter is always the correct HSV representation of the former's RGB colour.
I am not sure what you are trying to do overall, so I can't really advise properly, but one thing you could do is "lie through your teeth" and tell PIL/Pillow that the image is RGB even though you know it is HSV. So if you do:
hsvimg = img.convert('HSV')
hsvimg.mode='RGB' # Tell PIL image is RGB
hsvimg.save('result.png')
it will save an image but it, and all other viewers, will show your Hue as Blue, your Saturation as Green and your Value as Blue.
I am guessing you have other processing to do, and this is only an intermediate aspect of your processing, so it probably won't matter and you can probably carry on and do your processing and convert back at the end and save to an sRGB PNG file without needing to lie.
In answer to your actual question, you can split and merge channels like this with PIL/Pillow:
# Split and recombine with PIL
r,g,b = img.split()
merged = Image.merge(mode='RGB',bands=(r,g,b)))
Or, if you prefer Numpy which is often faster:
# Open image as Numpy array
img = np.array(Image.open('start.png'))
# Split into 3 channels/arrays/bands
r = img[:, :, 0]
g = img[:, :, 1]
b = img[:, :, 2]
# Recombine to single image
merged = np.dstack((r, g, b))

How to select corresponding value in two data sets using matlab?

I have a two datasets (x,y) in in table:
x = [4.14;5.07;3.61;4.07;3.68;4.13;3.95;3.88;5.41;6.14]
y = [69.78;173.07;19.28;32.88;15.87;53.73;41.69;35.14;228.08;267.11];
tb = table(x,y)
edges = linspace(30, 0, 61);
Based on this I have written following program
for k = 1:length(x)
New(k) = find(x(k)>edges,1,'last');
end
I want to see datasets y which satisfying condition of of above x values.

How can I get result with array in Sympy

I am tring to get countour chart with sympy
I'm tring something like below but subs does not take array
and I tried for lambapy but lamdafy does not take 2 symbols or I don't know how to.
X,Y, formula = symbols('X Y formula')
formula = sp.sympify('X*2 + Y*3 +7*X*Y +34')
x = numpy.arange(1,10,1)
y = numpy.arange(1,10,1)
XValue,YValue = meshgrid(x,y)
ZValue = formula.sub([(X,XValue),(Y,YValue)])
Plot.contour(XValue, YValue, ZValue)
Are there any way to get result form 2 or more symbol with arrays
Answer was to lambdify the formula and get the result Z first. Then put XYZ value into the chart
X,Y, formula = symbols('X Y formula')
formula = sp.sympify('X*2 + Y*3 +7*X*Y +34')
x = numpy.arange(1,10,1)
y = numpy.arange(1,10,1)
XValue,YValue = meshgrid(x,y)
T = lambdify((x,y), formula,'numpy')
ZValue = T(XValue,YValue )
Plot.contour(XValue, YValue, ZValue)

Trouble datamining with Django

I've set up a Django project in which i create random points. These random points are stored in a database(sqlite) (i can see them via the admin website and change the values, so this works).
If i the write a script i can access the points and print them in a plot. See code below.
But if I then want to mine these points to sort them or only plot a selection of the dataset i seem to have trouble. If i readout the values they are not connected anymore and sorting x would mix up the point set.
Is there a way to sort the data set to a minimum value of in this case X and the sort the values and print the set? (keep all x, y, z and name value of the point intact?) (see answer below, point in Point3D.objects.all().order_by('x'):)
If i now want to to have the values of x between x = 12 and x = 30? how can i add this extra filter?
My code is as follows:
models.py:
class Point3D(models.Model):
name = models.CharField(max_length = 10)
x = models.DecimalField(max_digits=5, decimal_places=2)
y = models.DecimalField(max_digits=5, decimal_places=2)
z = models.DecimalField(max_digits=5, decimal_places=2)
generate the points:
from books.models import Point3D
def points():
for i in range(20):
x = random.randint(0,100)
y = random.randint(0,100)
z = random.randint(0,100)
p = Point3D(name = x , x = x ,y = y,z = z)
# print 'test'
p.save()
#
points()
in views.py:
def ThreeGraphs(request):
fig = Figure()
fig.suptitle('2D-punten')
ax = fig.add_subplot(111)
for point in Point3D.objects.all():
print point
name = int(point.name)
xs = int(point.x)
ys = int(point.y)
zs = int(point.z)
print (xs, ys, zs)
ax.plot(xs, ys, 'bo' )
HttpResponse(mimetype="image/png")
FigureCanvas(fig)
fig.savefig('template/images/testing.png')
picture = "testing.png"
return render_to_response('Test.html', {'picture': picture}, RequestContext(request))
Hope anyone knows how to solve my trouble.
Thanks a lot!
Tijl
You need to to this:
for point in Point3D.objects.all().order_by('x'):
This will return the points in sorted order by the 'x' field. You can say order_by('-x') to reverse the sort order.

Resources