当前位置:首页 » 编程语言 » python保存多张图片

python保存多张图片

发布时间: 2023-10-09 13:03:54

python 画图存储(savefig)

你可以安装python的第三方应用chartdirector,如下面用python代码生成多个曲线的png图形,并可以自定义layout.


#!/usr/bin/python
from pychartdir import *

# The data for the line chart
data0 = [42, 49, 33, 38, 51, 46, 29, 41, 44, 57, 59, 52, 37, 34, 51, 56, 56, 60, 70,
76, 63, 67, 75, 64, 51]
data1 = [50, 55, 47, 34, 42, 49, 63, 62, 73, 59, 56, 50, 64, 60, 67, 67, 58, 59, 73,
77, 84, 82, 80, 84, 98]
data2 = [36, 28, 25, 33, 38, 20, 22, 30, 25, 33, 30, 24, 28, 15, 21, 26, 46, 42, 48,
45, 43, 52, 64, 60, 70]

# The labels for the line chart
labels = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13",
"14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24"]

# Create an XYChart object of size 600 x 300 pixels, with a light blue (EEEEFF)
# background, black border, 1 pxiel 3D border effect and rounded corners
c = XYChart(600, 300, 0xeeeeff, 0x000000, 1)
c.setRoundedFrame()

# Set the plotarea at (55, 58) and of size 520 x 195 pixels, with white background.
# Turn on both horizontal and vertical grid lines with light grey color (0xcccccc)
c.setPlotArea(55, 58, 520, 195, 0xffffff, -1, -1, 0xcccccc, 0xcccccc)

# Add a legend box at (50, 30) (top of the chart) with horizontal layout. Use 9 pts
# Arial Bold font. Set the background and border color to Transparent.
c.addLegend(50, 30, 0, "arialbd.ttf", 9).setBackground(Transparent)

# Add a title box to the chart using 15 pts Times Bold Italic font, on a light blue
# (CCCCFF) background with glass effect. white (0xffffff) on a dark red (0x800000)
# background, with a 1 pixel 3D border.
c.addTitle("Application Server Throughput", "timesbi.ttf", 15).setBackground(
0xccccff, 0x000000, glassEffect())

# Add a title to the y axis
c.yAxis().setTitle("MBytes per hour")

# Set the labels on the x axis.
c.xAxis().setLabels(labels)

# Display 1 out of 3 labels on the x-axis.
c.xAxis().setLabelStep(3)

# Add a title to the x axis
c.xAxis().setTitle("Jun 12, 2006")

# Add a line layer to the chart
layer = c.addLineLayer2()

# Set the default line width to 2 pixels
layer.setLineWidth(2)

# Add the three data sets to the line layer. For demo purpose, we use a dash line
# color for the last line
layer.addDataSet(data0, 0xff0000, "Server #1")
layer.addDataSet(data1, 0x008800, "Server #2")
layer.addDataSet(data2, c.dashLineColor(0x3333ff, DashLine), "Server #3")

# Output the chart
c.makeChart("multiline.png")

② python处理图片数据

目录

1.机器是如何存储图像的?

2.在Python中读取图像数据

3.从图像数据中提取特征的方法#1:灰度像素值特征

4.从图像数据中提取特征的方法#2:通道的平均像素值

5.从图像数据中提取特征的方法#3:提取边缘
是一张数字8的图像,仔细观察就会发现,图像是由小方格组成的。这些小方格被称为像素。

但是要注意,人们是以视觉的形式观察图像的,可以轻松区分边缘和颜色,从而识别图片中的内容。然而机器很难做到这一点,它们以数字的形式存储图像。请看下图:

机器以数字矩阵的形式储存图像,矩阵大小取决于任意给定图像的像素数。

假设图像的尺寸为180 x 200或n x m,这些尺寸基本上是图像中的像素数(高x宽)。

这些数字或像素值表示像素的强度或亮度,较小的数字(接近0)表示黑色,较大的数字(接近255)表示白色。通过分析下面的图像,读者就会弄懂到目前为止所学到的知识。

下图的尺寸为22 x 16,读者可以通过计算像素数来验证:

图片源于机器学习应用课程

刚才讨论的例子是黑白图像,如果是生活中更为普遍的彩色呢?你是否认为彩色图像也以2D矩阵的形式存储?

彩色图像通常由多种颜色组成,几乎所有颜色都可以从三原色(红色,绿色和蓝色)生成。

因此,如果是彩色图像,则要用到三个矩阵(或通道)——红、绿、蓝。每个矩阵值介于0到255之间,表示该像素的颜色强度。观察下图来理解这个概念:

图片源于机器学习应用课程

左边有一幅彩色图像(人类可以看到),而在右边,红绿蓝三个颜色通道对应三个矩阵,叠加三个通道以形成彩色图像。

请注意,由于原始矩阵非常大且可视化难度较高,因此这些不是给定图像的原始像素值。此外,还可以用各种其他的格式来存储图像,RGB是最受欢迎的,所以笔者放到这里。读者可以在此处阅读更多关于其他流行格式的信息。

用Python读取图像数据

下面开始将理论知识付诸实践。启动Python并加载图像以观察矩阵:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
from skimage.io import imread, imshow
image = imread('image_8_original.png', as_gray=True)
imshow(image)

#checking image shape
image.shape, image

(28,28)

矩阵有784个值,而且这只是整个矩阵的一小部分。用一个LIVE编码窗口,不用离开本文就可以运行上述所有代码并查看结果。

下面来深入探讨本文背后的核心思想,并探索使用像素值作为特征的各种方法。

方法#1:灰度像素值特征

从图像创建特征最简单的方法就是将原始的像素用作单独的特征。

考虑相同的示例,就是上面那张图(数字‘8’),图像尺寸为28×28。

能猜出这张图片的特征数量吗?答案是与像素数相同!也就是有784个。

那么问题来了,如何安排这784个像素作为特征呢?这样,可以简单地依次追加每个像素值从而生成特征向量。如下图所示:

下面来用Python绘制图像,并为该图像创建这些特征:

image = imread('puppy.jpeg', as_gray=True)

image.shape, imshow(image)

(650,450)

该图像尺寸为650×450,因此特征数量应为297,000。可以使用NumPy中的reshape函数生成,在其中指定图像尺寸:

#pixel features

features = np.reshape(image, (660*450))

features.shape, features

(297000,)
array([0.96470588, 0.96470588, 0.96470588, ..., 0.96862745, 0.96470588,
0.96470588])

这里就得到了特征——长度为297,000的一维数组。很简单吧?在实时编码窗口中尝试使用此方法提取特征。

但结果只有一个通道或灰度图像,对于彩色图像是否也可以这样呢?来看看吧!

方法#2:通道的平均像素值

在读取上一节中的图像时,设置了参数‘as_gray = True’,因此在图像中只有一个通道,可以轻松附加像素值。下面删除参数并再次加载图像:

image = imread('puppy.jpeg')
image.shape

(660, 450, 3)

这次,图像尺寸为(660,450,3),其中3为通道数量。可以像之前一样继续创建特征,此时特征数量将是660*450*3 = 891,000。

或者,可以使用另一种方法:

生成一个新矩阵,这个矩阵具有来自三个通道的像素平均值,而不是分别使用三个通道中的像素值。

下图可以让读者更清楚地了解这一思路:

这样一来,特征数量保持不变,并且还能考虑来自图像全部三个通道的像素值。

image = imread('puppy.jpeg')
feature_matrix = np.zeros((660,450))
feature_matrix.shape

(660, 450)

现有一个尺寸为(660×450×3)的三维矩阵,其中660为高度,450为宽度,3是通道数。为获取平均像素值,要使用for循环:

for i in range(0,iimage.shape[0]):
for j in range(0,image.shape[1]):
feature_matrix[i][j] = ((int(image[i,j,0]) + int(image[i,j,1]) + int(image[i,j,2]))/3)

新矩阵具有相同的高度和宽度,但只有一个通道。现在,可以按照与上一节相同的步骤进行操作。依次附加像素值以获得一维数组:

features = np.reshape(feature_matrix, (660*450))
features.shape

(297000,)

方法#3:提取边缘特征

请思考,在下图中,如何识别其中存在的对象:

识别出图中的对象很容易——狗、汽车、还有猫,那么在区分的时候要考虑哪些特征呢?形状是一个重要因素,其次是颜色,或者大小。如果机器也能像这样识别形状会怎么样?

类似的想法是提取边缘作为特征并将其作为模型的输入。稍微考虑一下,要如何识别图像中的边缘呢?边缘一般都是颜色急剧变化的地方,请看下图:

笔者在这里突出了两个边缘。这两处边缘之所以可以被识别是因为在图中,可以分别看到颜色从白色变为棕色,或者由棕色变为黑色。如你所知,图像以数字的形式表示,因此就要寻找哪些像素值发生了剧烈变化。

假设图像矩阵如下:

图片源于机器学习应用课程

该像素两侧的像素值差异很大,于是可以得出结论,该像素处存在显着的转变,因此其为边缘。现在问题又来了,是否一定要手动执行此步骤?

当然不!有各种可用于突出显示图像边缘的内核,刚才讨论的方法也可以使用Prewitt内核(在x方向上)来实现。以下是Prewitt内核:

获取所选像素周围的值,并将其与所选内核(Prewitt内核)相乘,然后可以添加结果值以获得最终值。由于±1已经分别存在于两列之中,因此添加这些值就相当于获取差异。

还有其他各种内核,下面是四种最常用的内核:

图片源于机器学习应用课程

现在回到笔记本,为同一图像生成边缘特征:

#importing the required libraries
import numpy as np
from skimage.io import imread, imshow
from skimage.filters import prewitt_h,prewitt_v
import matplotlib.pyplot as plt
%matplotlib inline

#reading the image
image = imread('puppy.jpeg',as_gray=True)

#calculating horizontal edges using prewitt kernel
edges_prewitt_horizontal = prewitt_h(image)
#calculating vertical edges using prewitt kernel
edges_prewitt_vertical = prewitt_v(image)

imshow(edges_prewitt_vertical, cmap='gray')

③ python中ls【】【】是什么意思



【CSDN 编者按】Python 风头正盛,未来一段时间内想必也会是热门编程语言之一。因此,熟练掌握 Python 对开发者来说极其重要,说不定能给作为开发者的你带来意想不到的财富。

作者 | Sebastian Opałczyński

编译 | 弯月 责编 | 张文

出品 | CSDN(ID:CSDNnews)

在本文中,我们来看一看日常工作中经常使用的一些 Python 小技巧。


集合

开发人员常常忘记 Python 也有集合数据类型,大家都喜欢使用列表处理一切。

集合(set)是什么?简单来说就是:集合是一组无序事物的汇集,不包含重复元素。

如果你熟练掌握集合及其逻辑,那么很多问题都可以迎刃而解。举个例子,如何获取一个单词中出现的字母?

myword = "NanananaBatman"set(myword){'N', 'm', 'n', 'B', 'a', 't'}

就这么简单,问题解决了,这个例子就来自 Python 的官方文档,大可不必过于惊讶。

再举一个例子,如何获取一个列表的各个元素,且不重复?

# first you can easily change set to list and other way aroundmylist = ["a", "b", "c","c"]# let's make a set out of itmyset = set(mylist)# myset will be:{'a', 'b', 'c'}# and, it's already iterable so you can do:for element in myset:print(element)# but you can also convert it to list again:mynewlist = list(myset)# and mynewlist will be:['a', 'b', 'c']

我们可以看到,“c”元素不再重复出现了。只有一个地方你需要注意,mylist 与 mynewlist 之间的元素顺序可能会有所不同:

mylist = ["c", "c", "a","b"]mynewlist = list(set(mylist))# mynewlist is:['a', 'b', 'c']

可以看出,两个列表的元素顺序不同。

下面,我们来进一步深入。

假设某些实体之间有一对多的关系,举个更加具体的例子:用户与权限。通常,一个用户可以拥有多个权限。现在假设某人想要修改多个权限,即同时添加和删除某些权限,应当如何解决这个问题?

# this is the set of permissions before change;original_permission_set = {"is_admin","can_post_entry", "can_edit_entry", "can_view_settings"}# this is new set of permissions;new_permission_set = {"can_edit_settings","is_member", "can_view_entry", "can_edit_entry"}# now permissions to add will be:new_permission_set.difference(original_permission_set)# which will result:{'can_edit_settings', 'can_view_entry', 'is_member'}# As you can see can_edit_entry is in both sets; so we do notneed# to worry about handling it# now permissions to remove will be:original_permission_set.difference(new_permission_set)# which will result:{'is_admin', 'can_view_settings', 'can_post_entry'}# and basically it's also true; we switched admin to member, andadd# more permission on settings; and removed the post_entrypermission

总的来说,不要害怕使用集合,它们能帮助你解决很多问题,更多详情,请参考 Python 官方文档。


日历

当开发与日期和时间有关的功能时,有些信息可能非常重要,比如某一年的这个月有多少天。这个问题看似简单,但是我相信日期和时间是一个非常有难度的话题,而且我觉得日历的实现问题非常多,简直就是噩梦,因为你需要考虑大量的极端情况。

那么,究竟如何才能找出某个月有多少天呢?

import calendarcalendar.monthrange(2020, 12)# will result:(1, 31)# BUT! you need to be careful here, why? Let's read thedocumentation:help(calendar.monthrange)# Help on function monthrange in mole calendar:# monthrange(year, month)# Return weekday (0-6~ Mon-Sun) and number of days (28-31) for# year, month.# As you can see the first value returned in tuple is a weekday,# not the number of the first day for a given month; let's try# to get the same for 2021calendar.monthrange(2021, 12)(2, 31)# So this basically means that the first day of December 2021 isWed# and the last day of December 2021 is 31 (which is obvious,cause# December always has 31 days)# let's play with Februarycalendar.monthrange(2021, 2)(0, 28)calendar.monthrange(2022, 2)(1, 28)calendar.monthrange(2023, 2)(2, 28)calendar.monthrange(2024, 2)(3, 29)calendar.monthrange(2025, 2)(5, 28)# as you can see it handled nicely the leap year;

某个月的第一天当然非常简单,就是 1 号。但是,“某个月的第一天是周X”,如何使用这条信息呢?你可以很容易地查到某一天是周几:

calendar.monthrange(2024, 2)(3, 29)# means that February 2024 starts on Thursday# let's define simple helper:weekdays = ["Monday", "Tuesday","Wednesday", "Thursday", "Friday","Saturday", "Sunday"]# now we can do something like:weekdays[3]# will result in:'Thursday'# now simple math to tell what day is 15th of February 2020:offset = 3 # it's thefirst value from monthrangefor day in range(1, 29):print(day,weekdays[(day + offset - 1) % 7])1 Thursday2 Friday3 Saturday4 Sunday...18 Sunday19 Monday20 Tuesday21 Wednesday22 Thursday23 Friday24 Saturday...28 Wednesday29 Thursday# which basically makes sense;

也许这段代码不适合直接用于生产,因为你可以使用 datetime 更容易地查找星期:

from datetime import datetimemydate = datetime(2024, 2, 15)datetime.weekday(mydate)# will result:3# or:datetime.strftime(mydate, "%A")'Thursday'

总的来说,日历模块有很多有意思的地方,值得慢慢学习:

# checking if year is leap:calendar.isleap(2021) #Falsecalendar.isleap(2024) #True# or checking how many days will be leap days for given yearspan:calendar.leapdays(2021, 2026) # 1calendar.leapdays(2020, 2026) # 2# read the help here, as range is: [y1, y2), meaning that second# year is not included;calendar.leapdays(2020, 2024) # 1
枚举有第二个参数

是的,枚举有第二个参数,可能很多有经验的开发人员都不知道。下面我们来看一个例子:

mylist = ['a', 'b', 'd', 'c', 'g', 'e']for i, item in enumerate(mylist):print(i, item)# Will give:0 a1 b2 d3 c4 g5 e# but, you can add a start for enumeration:for i, item in enumerate(mylist, 16):print(i, item)# and now you will get:16 a17 b18 d19 c20 g21 e

第二个参数可以指定枚举开始的地方,比如上述代码中的 enumerate(mylist,16)。如果你需要处理偏移量,则可以考虑这个参数。


if-else 逻辑

你经常需要根据不同的条件,处理不同的逻辑,经验不足的开发人员可能会编写出类似下面的代码:

OPEN = 1IN_PROGRESS = 2CLOSED = 3def handle_open_status():print('Handling openstatus')def handle_in_progress_status():print('Handling inprogress status')def handle_closed_status():print('Handling closedstatus')def handle_status_change(status):if status == OPEN:handle_open_status()elif status ==IN_PROGRESS:handle_in_progress_status()elif status == CLOSED:handle_closed_status()handle_status_change(1) #Handling open statushandle_status_change(2) #Handling in progress statushandle_status_change(3) #Handling closed status

虽然这段代码看上去也没有那么糟,但是如果有 20 多个条件呢?

那么,究竟应该怎样处理呢?

from enum import IntEnumclass StatusE(IntEnum):OPEN = 1IN_PROGRESS = 2CLOSED = 3def handle_open_status():print('Handling openstatus')def handle_in_progress_status():print('Handling inprogress status')def handle_closed_status():print('Handling closedstatus')handlers = {StatusE.OPEN.value:handle_open_status,StatusE.IN_PROGRESS.value: handle_in_progress_status,StatusE.CLOSED.value:handle_closed_status}def handle_status_change(status):if status not inhandlers:raiseException(f'No handler found for status: {status}')handler =handlers[status]handler()handle_status_change(StatusE.OPEN.value) # Handling open statushandle_status_change(StatusE.IN_PROGRESS.value) # Handling in progress statushandle_status_change(StatusE.CLOSED.value) # Handling closed statushandle_status_change(4) #Will raise the exception

在 Python 中这种模式很常见,它可以让代码看起来更加整洁,尤其是当方法非常庞大,而且需要处理大量条件时。


enum 模块

enum 模块提供了一系列处理枚举的工具函数,最有意思的是 Enum 和 IntEnum。我们来看个例子:

from enum import Enum, IntEnum, Flag, IntFlagclass MyEnum(Enum):FIRST ="first"SECOND ="second"THIRD ="third"class MyIntEnum(IntEnum):ONE = 1TWO = 2THREE = 3# Now we can do things like:MyEnum.FIRST ## it has value and name attributes, which are handy:MyEnum.FIRST.value #'first'MyEnum.FIRST.name #'FIRST'# additionally we can do things like:MyEnum('first') #, get enum by valueMyEnum['FIRST'] #, get enum by name

使用 IntEnum 编写的代码也差不多,但是有几个不同之处:

MyEnum.FIRST == "first" # False# butMyIntEnum.ONE == 1 # True# to make first example to work:MyEnum.FIRST.value == "first" # True

在中等规模的代码库中,enum 模块在管理常量方面可以提供很大的帮助。

enum 的本地化可能有点棘手,但也可以实现,我用django快速演示一下:

from enum import Enumfrom django.utils.translation import gettext_lazy as _class MyEnum(Enum):FIRST ="first"SECOND ="second"THIRD ="third"@classmethoddef choices(cls):return [(cls.FIRST.value, _('first')),(cls.SECOND.value, _('second')),(cls.THIRD.value, _('third'))# And later in eg. model definiton:some_field = models.CharField(max_length=10,choices=MyEnum.choices())


iPython

iPython 就是交互式 Python,它是一个交互式的命令行 shell,有点像 Python 解释器。

首先,你需要安装 iPython:


pip install ipython

接下来,你只需要在输入命令的时候,将 Python 换成 ipython:

# you should see something like this after you start:Python 3.8.5 (default, Jul 28 2020, 12:59:40)Type 'right', 'credits' or 'license' for more informationIPython 7.18.1 -- An enhanced Interactive Python. Type '?' forhelp.In [1]:

ipython 支持很多系统命令,比如 ls 或 cat,tab 键可以显示提示,而且你还可以使用上下键查找前面用过的命令。更多具体信息,请参见官方文档。

参考链接:https://levelup.gitconnected.com/python-tricks-i-can-not-live-without-87ae6aff3af8

④ python 怎么把爬到的图片保存下来

#建立单级目录
filename=r'E:\NASDownload\视频\一行代码爬视频\爬取图片以此
for i in range(0,len(imageinfo)):
path="{}{}{}{}".format(filename,'\\',i,'.jpg')
res=requests.get(url=imageinfo[i]).content
time.sleep(5)
with open(path,'wb') as f:
f.write(res)
f.close()

⑤ python opencv如何存图片到指定路径按图上的会存到python_work文件夹

如图,修改倒数第四行的内容为:
cv2.imwrite('F:/xxx/yyy/' + str(c) + '.jpg', frame)

即可将图片存储到 F 盘的 xxx\yyy 目录中,这里按照你的需要修改即可

热点内容
java知识点总结 发布:2025-02-01 09:08:32 浏览:684
如何在手机版给服务器加光影 发布:2025-02-01 09:02:14 浏览:727
简单神器安卓系统的哪个好 发布:2025-02-01 09:00:48 浏览:354
社保卡密码如何异地改密码 发布:2025-02-01 08:57:22 浏览:33
什么安卓平板最好能开120帧 发布:2025-02-01 08:55:58 浏览:380
安卓怎么冻结苹果id账号 发布:2025-02-01 08:45:16 浏览:639
pythonforosx 发布:2025-02-01 08:43:50 浏览:763
ftp建站工具 发布:2025-02-01 08:42:07 浏览:532
linux开启ntp 发布:2025-02-01 08:31:42 浏览:284
excel密码加密 发布:2025-02-01 08:17:01 浏览:539