>>> import numpy as np >>> import cv2 >>> import matplotlib as plt >>> import os >>> import time >>> def save_imginfo_to_txt(filepath, txtpath): ... files = os.listdir(filepath) ... res = [] ... for file in files: ... filename = filepath + "I:\\18Breakageratecalculation\\SVM run\\pos" + file ... img = cv2.imread(filename) ... res.append([filename, 1, 0, 0, img.shape[0], img.shape[1]]) ... save_txt = txtpath + "I:\\18Breakageratecalculation\\SVM run\\pos" + "file_name.txt" ... file = open(save_txt, 'a') ... for i in res: ... file.write(' '.join([str(j) for j in i])) ... file.write("\n") ... file.close() ... >>> filepath = r"I:\18Breakageratecalculation\SVM run\pos\" File "<stdin>", line 1 filepath = r"I:\18Breakageratecalculation\SVM run\pos\" ^ SyntaxError: unterminated string literal (detected at line 1) >>> filepath = r"I:\18Breakageratecalculation\SVM run\pos" >>> txtpath = r"I:\18Breakageratecalculation\SVM run" >>> save_imginfo_to_txt(filepath, txtpath) [ WARN:0@385.483] imread_('I:\18Breakageratecalculation\SVM run\posI:\18Breakageratecalculation\SVM run\pos1.png'): can't open/read file: check file path/integrity Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 7, in save_imginfo_to_txt AttributeError: 'NoneType' object has no attribute 'shape'
时间: 2023-06-16 07:03:47 浏览: 182
在你的代码中,有几个错误需要修正。
首先,在定义 `filepath` 时,你使用了反斜杠 `\` 来转义字符,但是最后一个反斜杠没有被转义,因此需要在字符串前加上 `r` 来表示 raw string,或者在最后一个反斜杠后面再加上一个反斜杠。
其次,在调用 `cv2.imread` 时,你传递的文件名是 `filename`,但是其中包含了 `filepath`,因此实际上会读取到 `filepath + filename`,导致文件路径错误。你需要将 `filename` 中的 `filepath` 去掉,只保留文件名。
最后,在处理图片时,如果读取失败,`cv2.imread` 会返回 `None`,因此需要加上判断。如果读取成功,才能获取其形状。
下面是修改后的代码:
```
import numpy as np
import cv2
import matplotlib as plt
import os
import time
def save_imginfo_to_txt(filepath, txtpath):
files = os.listdir(filepath)
res = []
for file in files:
filename = filepath + "\\" + file
img = cv2.imread(filename)
if img is not None:
res.append([filename, 1, 0, 0, img.shape[0], img.shape[1]])
save_txt = txtpath + "\\" + "file_name.txt"
file = open(save_txt, 'a')
for i in res:
file.write(' '.join([str(j) for j in i]))
file.write("\n")
file.close()
filepath = r"I:\18Breakageratecalculation\SVM run\pos"
txtpath = r"I:\18Breakageratecalculation\SVM run"
save_imginfo_to_txt(filepath, txtpath)
```
请注意,这里的代码只是修正了语法错误,并不能保证程序的正确性,你需要根据你的需求进一步修改。
阅读全文