简体   繁体   中英

How to remove exponential (scientific notation) when printing NumPy array alements?

My code computes Hu moments on .tiff image. I need to remove exponential (scientific) notation in the output, looking like:

2.84737313535e-05
1.25610416364e-09
1.25419253619e-09
1.57419718046e-18
6.69242940524e-12
4.17512050223e-22

  def humoments(self):               #function for HuMoments computation
     for filename in glob.iglob ('*.tif'):
      img = cv.LoadImageM(filename, cv.CV_LOAD_IMAGE_GRAYSCALE)
      cancer = cv.GetHuMoments(cv.Moments(img))
      #arr = cancer
      arr = numpy.array([cancer])
     with open('hu.csv', 'wb') as csvfile:
      for elem in arr.flat[:50]:
    #print('{}\t'.format(elem))  #this code puts the result to console
       writer = csv.writer(csvfile, delimiter=' ', quotechar='|',        quoting=csv.QUOTE_MINIMAL)
       writer.writerow([('{}\t'.format(elem))])

Thank you for helping me

Change

writer.writerow([('{}\t'.format(elem))])

To

writer.writerow([('{0:.10f}\t'.format(elem))])

Here you can find explanation of string formatting in Python.

Instead of using csv to create the file, you could call np.savetxt :

>>> import numpy as np
>>> arr = np.array([2.84e-05, 6.69e-12])
>>> np.savetxt('/tmp/out', arr, fmt='%.14f')

produces

0.00002840000000
0.00000000000669

So in your case, to write out the first 50 elements of arr use:

np.savetxt('hu.csv', arr.flat[:50], fmt='%.14f')

instead of

with open('hu.csv', 'wb') as csvfile:
  for elem in arr.flat[:50]:
#print('{}\t'.format(elem))  #this code puts the result to console
   writer = csv.writer(csvfile, delimiter=' ', quotechar='|',        quoting=csv.QUOTE_MINIMAL)
   writer.writerow([('{}\t'.format(elem))])

Note: Unlike your original code, np.savetxt will not put a tab at the end of each line. But then, why would you want one?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM