python ioerror 22_python - IOError:[Errno 22]无效模式('rb')或文件名:'\\ x89PNG \\ n' - 堆栈内存溢出...

我刚刚开始使用Python进行编程,因为我需要开发一种可执行程序来执行直径分布。 我设法找到了可行的方法(下面的代码):

# Put here all modules you would need in order to represent your data

import matplotlib.pylab as plt

import numpy as np

import collections as c

from collections import Counter

from PIL import Image

import matplotlib.mlab as mlab

from scipy.optimize import curve_fit

import Tkinter as tk

from tkFileDialog import askopenfilename

# This prints the plot containing the diameter distribution of our sample

root = tk.Tk() ; root.withdraw()

filename = askopenfilename(parent=root)

f = open(filename)

with f as input: #Change the Results.txt file for your own .txt file

a = zip(*(line.strip().split('\t') for i,line in enumerate(input) if i != 0))

areas = a[1]

diam = []

for area in areas:

diam.append(round((np.sqrt(float(area)/ np.pi) * 2), 3)) # The number 3 tells us how many decimals will be shown

hist, bins = np.histogram(diam, 50)

diam.sort()

counts = c.Counter(diam)

'''This prints the table which includes all diameter values

and how many of them we can find on our sample# '''

table = sorted(counts.items())

col_labels = ['Diameter (nm)', 'Counts'] # In Diameter column you can add the units inside the empty parenthesis

table_vals = table

q = diam

mu = sum(q)/float(len(q))

variance = np.var(q)

sigma = np.sqrt(variance)

# In the plt.suptitle part --> change the default name to your sample name

plt.subplot(121)

plt.bar(counts.keys(), counts.values(), 0.01, color="black")

plt.tick_params(direction = 'out', labeltop='off', labelright='off')

plt.xlabel('Diameter (nm)', fontsize=16, fontweight='bold')

plt.ylabel('Count (a.u.)', fontsize=16, fontweight='bold')

plt.title(r'$\mathregular{Diameter \ distribution\ of \ the\ sample:}\ \mu=%.3f,\ \sigma=%.3f$' % (mu, sigma), fontsize=18, fontweight='bold')

plt.suptitle('Silicon nanopillars grown epitaxially', fontsize=22, fontweight='bold')

plt.autoscale(enable=True, axis='x', tight=None)

the_table = plt.table(cellText = table_vals, colLabels = col_labels, loc = 'bottom', cellLoc = 'center', bbox = [0.67, 0.18, 0.30, 0.8])

the_table.auto_set_font_size(False)

the_table.set_fontsize(12)

# This adds a gaussian fit to our histogram

plt.plot()

x = diam

yhist, xhist = np.histogram(x, bins=np.arange(4096))

xh = np.where(yhist > 0)[0]

yh = yhist[xh]

def gaussian(x, a, mu, sigma):

return a * np.exp(-((x - mu)**2 / (2 * sigma**2)))

popt, pcov = curve_fit(gaussian, xh, yh, [1, mu, sigma])

i = np.linspace(min(diam)-20, max(diam), 1000)

plt.plot(i, gaussian(i, *popt), lw=3, ls=':', c='r')

plt.xlim(min(diam)-10, max(diam)+10)

# This adds the image from where the data is extracted (always use .png images otherwise this won't work)

im = Image.open('Dosi05.png') # Put here the original image

im2 = Image.open('Dosi05_Analyzed.png') # Put here the thresholded and analysed image

plt.subplot(222)

plt.imshow(im, cmap='gray')

plt.axis('off')

plt.title('Original Image', fontsize=14, fontweight='bold')

plt.subplot(224)

plt.imshow(im2, cmap='gray')

plt.axis('off')

plt.title('Processed Image', fontsize=14, fontweight='bold')

plt.show()

但是我被要求做与.txt文件相同的操作,但要使用plt.subplot(222)和plt.subplot(224)绘制图像,以避免触及代码。

我也尝试使用Tkinter做类似的事情(请参见下面的代码):

# Put here all modules you would need in order to represent your data

import matplotlib.pylab as plt

import numpy as np

import collections as c

from collections import Counter

from PIL import Image

import matplotlib.mlab as mlab

from scipy.optimize import curve_fit

import Tkinter as tk

from tkFileDialog import askopenfilename, askopenfile

from skimage import data

# This prints the plot containing the diameter distribution of our sample

root = tk.Tk() ; root.withdraw()

filename = askopenfilename(parent=root)

f = open(filename)

with f as input: #Change the Results.txt file for your own .txt file

a = zip(*(line.strip().split('\t') for i,line in enumerate(input) if i != 0))

areas = a[1]

diam = []

for area in areas:

diam.append(round((np.sqrt(float(area)/ np.pi) * 2), 3)) # The number 3 tells us how many decimals will be shown

hist, bins = np.histogram(diam, 50)

diam.sort()

counts = c.Counter(diam)

'''This prints the table which includes all diameter values

and how many of them we can find on our sample# '''

table = sorted(counts.items())

col_labels = ['Diameter (nm)', 'Counts'] # In Diameter column you can add the units inside the empty parenthesis

table_vals = table

q = diam

mu = sum(q)/float(len(q))

variance = np.var(q)

sigma = np.sqrt(variance)

# In the plt.suptitle part --> change the default name to your sample name

plt.subplot(121)

plt.bar(counts.keys(), counts.values(), 0.01, color="black")

plt.tick_params(direction = 'out', labeltop='off', labelright='off')

plt.xlabel('Diameter (nm)', fontsize=16, fontweight='bold')

plt.ylabel('Count (a.u.)', fontsize=16, fontweight='bold')

plt.title(r'$\mathregular{Diameter \ distribution\ of \ the\ sample:}\ \mu=%.3f,\ \sigma=%.3f$' % (mu, sigma), fontsize=18, fontweight='bold')

plt.suptitle('Silicon nanopillars grown epitaxially', fontsize=22, fontweight='bold')

plt.autoscale(enable=True, axis='x', tight=None)

the_table = plt.table(cellText = table_vals, colLabels = col_labels, loc = 'bottom', cellLoc = 'center', bbox = [0.67, 0.18, 0.30, 0.8])

the_table.auto_set_font_size(False)

the_table.set_fontsize(12)

# This adds a gaussian fit to our histogram

plt.plot()

x = diam

yhist, xhist = np.histogram(x, bins=np.arange(4096))

xh = np.where(yhist > 0)[0]

yh = yhist[xh]

def gaussian(x, a, mu, sigma):

return a * np.exp(-((x - mu)**2 / (2 * sigma**2)))

popt, pcov = curve_fit(gaussian, xh, yh, [1, mu, sigma])

i = np.linspace(min(diam)-20, max(diam), 1000)

plt.plot(i, gaussian(i, *popt), lw=3, ls=':', c='r')

plt.xlim(min(diam)-10, max(diam)+10)

# This adds the image from where the data is extracted (always use .png images otherwise this won't work)

image_formats = [('PNG','*.png')]

file_path_list = askopenfilename(filetypes=image_formats, initialdir='/', title='Please select a picture to analyze')

for file_path in file_path_list:

image = data.imread(file_path)

image2 = data.imread(file_path)

plt.subplot(222)

plt.imshow(image, cmap='gray')

plt.axis('off')

plt.title('Original Image', fontsize=14, fontweight='bold')

plt.subplot(224)

plt.imshow(image2, cmap='gray')

plt.axis('off')

plt.title('Processed Image', fontsize=14, fontweight='bold')

plt.show()

但是在选择了第一个图像文件之后,Python向我抛出以下内容:

[IO错误:[错误22]无效的模式( 'RB')或文件名: '\\ x89PNG \\ N' 1

有人可以告诉我如何解决此问题,或者是否有其他方法可以通过从文件浏览器中选择而不是在代码本身中进行更改来显示图像?

希望这个问题足够清楚,谢谢您的提前帮助!

ÿ

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值