I'm trying to plot an svg image but it's showing up inverted, would anyone know how to fix this?
Input
<img src="https://static.wikia.nocookie.net/ptstarwars/images/9/9d/Jedi_symbol.svg" alt="drawing" style="width:200px;"/>
Code
import svgpathtools
import numpy as np
import matplotlib.pyplot as plt
svgpaths, attributes = svgpathtools.svg2paths('./jedi_symbol.svg')
paths = []
for n, (attrs, svgpath) in enumerate(zip(attributes, svgpaths)):
path = []
for segment in svgpath:
num_steps = int(segment.length()/0.5)
tt = np.linspace(0, 1, num_steps)
xy = np.array([segment.point(t) for t in tt])
if len(xy) > 0:
if path and xy[0] == path[-1]:
xy = xy[1:]
path.extend(xy)
paths.append(np.array(path))
paths = np.array(paths)
x_table, y_table = paths[0].real, paths[0].imag
# Simple method to center the image
x_table = x_table - min(x_table)
y_table = y_table - min(y_table)
x_table = x_table - max(x_table) / 2
y_table = y_table - max(y_table) / 2
fig, ax = plt.subplots(figsize=(5, 5))
ax.set_aspect('equal', 'datalim')
ax.plot(x_table, y_table)
Output
It just multiply the y by -1
ax.plot(x_table, -1*y_table)
Related
I am trying to create a 2D colored bar chart
import numpy as np
import matplotlib.pyplot as plt
import pickle
from graphviz import Digraph
from torch.autograd import Variable
import argparse
def make_dot(var):
'''
Visualization of the computation graph
Taken from : https://github.com/szagoruyko/functional-zoo/blob/master/visualize.py
'''
node_attr = dict(style='filled',
shape='box',
align='left',
fontsize='12',
ranksep='0.1',
height='0.2')
dot = Digraph(node_attr=node_attr, graph_attr=dict(size="12,12"))
seen = set()
def add_nodes(var):
if var not in seen:
if isinstance(var, Variable):
value = '('+(', ').join(['%d' % v for v in var.size()])+')'
dot.node(str(id(var)), str(value), fillcolor='lightblue')
else:
dot.node(str(id(var)), str(type(var).__name__))
seen.add(var)
if hasattr(var, 'previous_functions'):
for u in var.previous_functions:
dot.edge(str(id(u[0])), str(id(var)))
add_nodes(u[0])
add_nodes(var.creator)
return dot
def plot_trajectories(true_trajs, pred_trajs, nodesPresent, obs_length, name, plot_directory, withBackground=False):
'''
Parameters
==========
true_trajs : Numpy matrix of shape seq_length x numNodes x 2
Contains the true trajectories of the nodes
pred_trajs : Numpy matrix of shape seq_length x numNodes x 2
Contains the predicted trajectories of the nodes
nodesPresent : A list of lists, of size seq_length
Each list contains the nodeIDs present at that time-step
obs_length : Length of observed trajectory
name : Name of the plot
withBackground : Include background or not
'''
traj_length, numNodes, _ = true_trajs.shape
# Initialize figure
plt.figure()
# Load the background
# im = plt.imread('plot/background.png')
# if withBackground:
# implot = plt.imshow(im)
# width_true = im.shape[0]
# height_true = im.shape[1]
# if withBackground:
# width = width_true
# height = height_true
# else:
width = 1
height = 1
traj_data = {}
for tstep in range(traj_length):
pred_pos = pred_trajs[tstep, :]
true_pos = true_trajs[tstep, :]
for ped in range(numNodes):
if ped not in traj_data and tstep < obs_length:
traj_data[ped] = [[], []]
if ped in nodesPresent[tstep]:
traj_data[ped][0].append(true_pos[ped, :])
traj_data[ped][1].append(pred_pos[ped, :])
for j in traj_data:
c = np.random.rand(3, 1)
true_traj_ped = traj_data[j][0] # List of [x,y] elements
pred_traj_ped = traj_data[j][1]
true_x = [(p[0]+1)/2*height for p in true_traj_ped]
true_y = [(p[1]+1)/2*width for p in true_traj_ped]
pred_x = [(p[0]+1)/2*height for p in pred_traj_ped]
pred_y = [(p[1]+1)/2*width for p in pred_traj_ped]
plt.plot(true_x, true_y, color=c, linestyle='solid', marker='o')
plt.plot(pred_x, pred_y, color=c, linestyle='dashed', marker='x')
if not withBackground:
plt.ylim((1, 0))
plt.xlim((0, 1))
# plt.show()
if withBackground:
plt.savefig('plot_with_background/'+name+'.png')
else:
plt.savefig(plot_directory+'/'+name+'.png')
plt.gcf().clear()
plt.close()
def main():
parser = argparse.ArgumentParser()
# Experiments
parser.add_argument('--test_dataset', type=int, default=0,
help='test dataset index')
# Parse the parameters
args = parser.parse_args()
# Save directory
save_directory = 'save/'
save_directory += str(args.test_dataset) + '/'
plot_directory = 'plot/'
f = open(save_directory+'/results.pkl', 'rb')
results = pickle.load(f)
# print "Enter 0 (or) 1 for without/with background"
# withBackground = int(input())
withBackground = 1
for i in range(len(results)):
print i
name = 'sequence' + str(i)
plot_trajectories(results[i][0], results[i][1], results[i][2], results[i][3], name, plot_directory, withBackground)
if __name__ == '__main__':
main()
Now I am unable to debug the Invalid RGBA argument because I don't understand what is causing the error. I even tried to use random colors instead with colors = np.random.rand(91,91,4) and still the error persists.
I have checked Stack Overflow posts regarding Invalid RGBA argument (for example this, this, this and this) and none of them seems to answer my problem.
I want to know what could be causing this error. I am using the standard Anaconda distribution for Python on Ubuntu Mate 16.
Could it be that due to recent updates in Python, the solution as in the original Stack Overflow post becomes obsolete?
Just replace
c = np.random.rand(3, 1)
with this:
c = np.random.rand(3)
It removes the error. matplotlib expects (3,) or (4,) shape for the c argument.
I have two ndArray.
ex:
x = np.array([110,200, 500,100])
y = np.array([50,150,30,70])
Now based on their value I have created an image.
x_shape = np.max(x) #x_shape=500
y_shape = np.max(y) #y-shape=150
image = np.zeros((x_shape+1, y_shape+1))
according to my data now my image size is (501,151)
Now, How can I insert data from (x, y) as x,y pair? I mean for the pixel value:
(110,50), (200,150), (500,30), (100,70)
I want the image will be white and the rest pixel will be dark. How can I achieve this?
Based on OP's own answer, one can improve it by using a vectorized approach:
import numpy as np
import matplotlib.pyplot as plt
x = np.array([110,200, 500,100])
y = np.array([50,150,30,70])
x = np.floor(x / 10).astype(int)
y = np.floor(y / 10).astype(int)
x_shape = np.max(x) # x_shape = 500
y_shape = np.max(y) # y_shape = 150
image = np.zeros((x_shape + 10, y_shape + 10))
image[x, y] = 10
plt.imshow(image)
(To be fair, I did not understand from the question that this is what OP was after).
EDIT
To address the "visualization issue" without resizing from the comments:
import numpy as np
import matplotlib.pyplot as plt
x = np.array([110, 200, 500, 100])
y = np.array([50, 150, 30, 70])
x_shape = np.max(x)
y_shape = np.max(y)
image = np.zeros((x_shape + 1, y_shape + 1))
image[x, y] = 10
plt.figure(figsize=(20, 20))
plt.imshow(image.transpose(), interpolation='nearest', aspect='equal')
Well, I got the answer. It was easy and as I am new it makes me confused.
import numpy as np
import matplotlib.pyplot as plt
x = np.array([110,200, 500,100])
y = np.array([50,150,30,70])
x = np.floor(x/10).astype(int) #devided by 10 to reduce the img size
y = np.floor(y/10).astype(int) #devided by 10 to reduce the img size
x_shape = np.max(x) #x_shape=500
y_shape = np.max(y) #y-shape=150
image = np.zeros((x_shape+10, y_shape+10))
for x, y in zip(x,y):
image[x,y]=200
plt.imshow(image)
not sure exactly what do you need you may try
a = np.array([110, 200, 500, 100])
b = np.array([50, 150, 30, 70])
np.array([zip(x,y) for x,y in zip(a,b)])
pd.DataFrame(list(zipped))```
##or another representation
np.dstack((x,y))
both are taken from https://stackoverflow.com/questions/49461605/why-do-we-need-to-convert-a-zipped-object-into-a-list
[1]: https://stackoverflow.com/questions/49461605/why-do-we-need-to-convert-a-zipped-object-into-a-list
I am trying to read a series of .dcm files which are by default show axial view. Below is the code:
import os
import numpy as np
import pydicom as dicom
from matplotlib import pyplot as plt
root_dir = 'mydcomDir'
def sortDcm():
print('Given Path to the .dcm directory is: {}'.format(root_dir))
slices = [dicom.read_file(root_dir + '/' + s) for s in os.listdir(root_dir)]
slices.sort(key = lambda x: float(x.ImagePositionPatient[2]))
pos1 = slices[int(len(slices)/2)].ImagePositionPatient[2]
pos2 = slices[(int(len(slices)/2)) + 1].ImagePositionPatient[2]
diff = pos2 - pos1
# if diff > 0:
# slices = np.flipud(slices)
try:
slice_thickness = np.abs(slices[0].ImagePositionPatient[2] - slices[1].ImagePositionPatient[2])
except:
slice_thickness = np.abs(slices[0].SliceLocation - slices[1].SliceLocation)
for s in slices:
s.SliceThickness = slice_thickness
# print("from sorted dicom",len(slices))
return slices
dcms = sortDcm()
ref_dicom = dcms[0]
d_array = np.zeros((ref_dicom.Columns,ref_dicom.Rows, len(dcms)), dtype=ref_dicom.pixel_array.dtype)
for dcm in dcms:
d_array[:, :, dcms.index(dcm)] = dcm.pixel_array
# fig = plt.figure(figsize=(12,12))
# plt.subplot(1, 3, 1)
# plt.title("Coronal")
# plt.imshow(np.flipud(d_array[idx , :, :].T))
# plt.subplot(1, 3, 2)
# plt.title("Sagital")
# plt.imshow(np.flipud(d_array[:, idy, :].T))
# plt.subplot(1, 3, 3)
plt.title("axial")
plt.imshow(d_array[:, :, dcms.index(dcm)])
plt.pause(0.001)
As you can see from the code I could not figure out the relevant idx and idy for particular dcm file.
So my question is how to get sagittal and coronal cuts and plot them, given the axial cuts?
Thanks in advance.
Edit:
As #ColonelFazackerley answered perfectly. I am adding below line just to show how I used it.
# fill 3D array with the images from the files
for i, s in enumerate(slices):
img2d = s.pixel_array
img3d[:,:,i] = img2d
#then to view sagittal and coronal slices for each of the axial slice
for i, s in enumerate(slices):
img2d = s.pixel_array
img3d[:,:,i] = img2d
corId = corId-1
sagId = sagId-1
# plot 3 orthogonal slices
a1 = plt.subplot(1,3,1)
plt.title('Axial')
plt.imshow(img3d[:,:,i],'gray')
a1.set_aspect(ax_aspect)
a2 = plt.subplot(1,3,2)
plt.title('Sagittal')
plt.imshow(np.flipud(img3d[:,sagId,:].T),'gray')
a2.set_aspect(sag_aspect)
a3 = plt.subplot(1,3,3)
plt.imshow(np.flipud(img3d[corId,:,:].T),'gray')
a3.set_aspect(cor_aspect)
plt.title('Coronal')
plt.show()
plt.pause(0.001)
"""usage: reslice.py <glob>
where <glob> refers to a set of DICOM image files.
Example: python reslice.py "*.dcm". The quotes are needed to protect the glob
from your system and leave it for the script."""
import pydicom
import numpy as np
import matplotlib.pyplot as plt
import sys
import glob
# load the DICOM files
files=[]
print('glob: {}'.format(sys.argv[1]))
for fname in glob.glob(sys.argv[1], recursive=False):
print("loading: {}".format(fname))
files.append(pydicom.read_file(fname))
print("file count: {}".format(len(files)))
# skip files with no SliceLocation (eg scout views)
slices=[]
skipcount=0
for f in files:
if hasattr(f, 'SliceLocation'):
slices.append(f)
else:
skipcount = skipcount + 1
print("skipped, no SliceLocation: {}".format(skipcount))
# ensure they are in the correct order
slices = sorted(slices, key=lambda s: s.SliceLocation)
# pixel aspects, assuming all slices are the same
ps = slices[0].PixelSpacing
ss = slices[0].SliceThickness
ax_aspect = ps[1]/ps[0]
sag_aspect = ps[1]/ss
cor_aspect = ss/ps[0]
# create 3D array
img_shape = list(slices[0].pixel_array.shape)
img_shape.append(len(slices))
img3d=np.zeros(img_shape)
# fill 3D array with the images from the files
for i, s in enumerate(slices):
img2d = s.pixel_array
img3d[:,:,i] = img2d
# plot 3 orthogonal slices
a1 = plt.subplot(2,2,1)
plt.imshow(img3d[:,:,img_shape[2]//2])
a1.set_aspect(ax_aspect)
a2 = plt.subplot(2,2,2)
plt.imshow(img3d[:,img_shape[1]//2,:])
a2.set_aspect(sag_aspect)
a3 = plt.subplot(2,2,3)
plt.imshow(img3d[img_shape[0]//2,:,:].T)
a3.set_aspect(cor_aspect)
plt.show()
tested against series 2 from this example 3D CT data
http://www.pcir.org/researchers/54879843_20060101.html
edit note: accepted as an example into the pydicom project
https://github.com/pydicom/pydicom/blob/master/examples/image_processing/reslice.py
I'm writing a program that obtains plot data from a graph(JPEG).
Vertical axis is logarithmic.
I successfully made a program that understands horizontal and vertical axes as linear (not logarithmic), see the code below:
%matplotlib inline
from PIL import Image
from scipy import *
from pylab import *
im = array(Image.open('fig1.jpg'))
hh = im.shape[0]
ww = im.shape[2]
imshow(im)
print(im[100,0,:])
Col = array([255,0,0])#赤
bnd = 30
yax = linspace(0.5,2e-4,hh)
xax = linspace(1,14,ww)
for i in range(hh):
for j in range(ww):
im[i,j,:] = 255*(any(im[i,j,:]>Col+bnd) or any(im[i,j,:]<Col-bnd))
mapim = abs(im[:,:,0]/255-1).astype(bool)
yval = array([average(yax[mapim[:,t]]) for t in range(ww)])
rlt = interp(range(100),xax,yval)
I have no idea how to modify it to make it understand logarithmic axis.
Please help me.
You just need to convert the y max and min to log scale:
ymax_lin = log10(0.5)
ymin_lin = log10(2e-4)
yax = linspace(ymax_lin,ymin_lin,hh)
and convert back to linear the yval values at the end:
yval = 10**yval
The full working code is here:
%matplotlib inline
from PIL import Image
from scipy import *
from pylab import *
im = array(Image.open('fig1.jpg'))
hh = im.shape[0]
ww = im.shape[1]
imshow(im)
print(im[100,0,:])
Col = array([255,0,0])
bnd = 30
ymax_lin = log10(0.5)
ymin_lin = log10(2e-4)
yax = linspace(ymax_lin,ymin_lin,hh)
xax = linspace(1,14,ww)
for i in range(hh):
for j in range(ww):
im[i,j,:] = 255*(any(im[i,j,:]>Col+bnd) or any(im[i,j,:]<Col-bnd))
mapim = abs(im[:,:,0]/255-1).astype(bool)
yval = array([average(yax[mapim[:,t]]) for t in range(ww)])
yval = 10**yval
rlt = interp(range(100),xax,yval)
Mayavi and python are exiting, simple and very good.
12 hours of working to do something simple: texture! I can see the plane that I'm drawing but I can't see the image on it, it's all white. here is my code: I hope that someone could help me, thank you.
the Code:
from PIL import Image
import numpy as np
from mayavi import mlab
import vtk
im=Image.open('ortofoto90.jpg')
pixel_x, pixel_y = im.size
ext = [10, 20, 10, 20]
xstep = float(ext[1] - ext[0]) / float(pixel_x)
ystep = float(ext[3] - ext[2]) / float(pixel_y)
X, Y = np.mgrid[ext[0]:ext[1]:xstep,ext[2]:ext[3]:ystep]
def f(x,y):
return x+y
Z = f(X,Y)
surf = mlab.surf(X,Y,Z, color=(1.0,1.0,1.0))
#img = image_from_array(np.array(im))
texture_img = vtk.vtkTexture()
texture_img.interpolate=1
texture_img.input = 'ortofoto90.jpg'
surf.actor.enable_texture = True
surf.actor.tcoord_generator_mode = 'plane'
surf.actor.actor.texture = texture_img
mlab.show()