【发布时间】:2021-07-20 22:28:06
【问题描述】:
第一篇文章,对 python 来说相对较新
我希望循环浏览一个图像文件夹,裁剪一个部分/ROI,应用一些处理技术,然后将新图像保存在某处。
我有工作代码可以在循环中裁剪和保存多个图像(参见代码块 1)。
但是,在处理工作后,我似乎无法获得保存方面(参见代码块 2)。 它为最后一行提供了以下错误...AttributeError: 'numpy.ndarray' object has no attribute 'save'。
我可能(希望)真的很愚蠢,这很容易解决。
提前感谢您的帮助
代码块 1 - 适用于裁剪图像文件夹并保存
filepath = '/some/file/path/Frames/'
for filename in os.listdir(filepath):
if "." not in filename:
continue
ending = filename.split(".")[1]
if ending not in ["jpg", "gif", "png"]:
continue
try:
image = Image.open(os.path.join(filepath, filename))
except IOError as e:
print("Problem Opening", filepath, ":", e)
continue
image = image.crop((535, 40, 600, 90))
name, extension = os.path.splitext(filename)
print(name + '_cropped.jpg')
image.save(os.path.join('/some/file/path/Frames/Cropped', name + '_cropped.jpg'))
代码块 2 - 尝试在保存之前合并图像处理,但遇到我上面提到的错误
filepath = '/some/file/path/Frames/'
for filename in os.listdir(filepath):
if "." not in filename:
continue
ending = filename.split(".")[1]
if ending not in ["jpg", "gif", "png"]:
continue
try:
image = Image.open(os.path.join(filepath, filename))
except IOError as e:
print("Problem Opening", filepath, ":", e)
continue
image = image.crop((535, 40, 600, 90))
# Greyscale
image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# Blur
image = cv2.GaussianBlur(image, (3, 3), 0)
# Threshold
image = cv2.threshold(image, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]
# Morph open to remove noise and invert image
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))
image = cv2.morphologyEx(image, cv2.MORPH_OPEN, kernel, iterations=1)
image = 255 - image
name, extension = os.path.splitext(filename)
print(name + '_cropped.jpg')
image.save(os.path.join('/some/file/path/Frames/Cropped', name + '_cropped.jpg'))
【问题讨论】: