Search code examples
pythonnumpymatplotlibtkinterpydicom

TypeError: iteration over a 0-d array, using numpy and pydicom


I am trying to create a simple DICOM viewer, in which I plot the image using matplotlib and I want to show that same plot(which is a DICOM image) in tkinter, but when I run the code I get this error. please help. The error occurs when I try to plot a, but I believe it has something to do wuth the way I declared the values of x, y, and p

import pydicom
import matplotlib
matplotlib.use('TkAgg')
import numpy as np
from matplotlib.backends.backend_tkagg import 
FigureCanvasTkAgg
from matplotlib.figure import Figure
from tkinter import *
from pydicom.data import get_testdata_files

filename = get_testdata_files('000000.dcm')
dataset = pydicom.dcmread('000000.dcm')
data = dataset.pixel_array

class mclass:
  def __init__(self, window):
    self.window = window
    self.button=Button(window,text="check",command=self.plot)
    self.button.pack()

  def plot (self):
      if 'PixelData' in dataset:
          rows = int(dataset.Rows)
          cols = int(dataset.Columns)
      y=np.array(rows)
      x=np.array(cols)
      p=np.array(data)
      fig = Figure(figsize=(6,6))
      a = fig.add_subplot(111)
      a.plot(p, range(2+max(y)))

      canvas = FigureCanvasTkAgg(fig, master=self.window)
      canvas.get_tk_widget().pack()
      canvas.draw()

window = Tk()
start = mclass (window)
window.mainloop()

Solution

  • From the look of it your error lies here :

    y=np.array(rows)
    ...
    a.plot(p, range(2+max(y)))
    

    You ask for the max(y), but the ds.Rows and ds.Columns you use to instantiate x and y are scalar values (and to be doubly sure you use int(ds.Rows)). This means that both x and y will be a 0-dimensional array and this would explain the thrown error, presumably on max(y). Try :

    if 'PixelData' in dataset:
          rows = int(dataset.Rows)
          cols = int(dataset.Columns)
      y=rows
      x=cols
      p=np.array(data)
      fig = Figure(figsize=(6,6))
      a = fig.add_subplot(111)
      a.plot(p, range(2+y))