當前位置:首頁 » 編程語言 » 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 目錄中,這里按照你的需要修改即可

熱點內容
android監聽輸入法狀態 發布:2025-02-01 07:52:44 瀏覽:280
android仿58 發布:2025-02-01 07:52:41 瀏覽:889
ubuntu解壓zip文件 發布:2025-02-01 07:52:39 瀏覽:223
紅色物業競賽視頻腳本 發布:2025-02-01 07:39:56 瀏覽:715
我的世界領域伺服器 發布:2025-02-01 07:30:06 瀏覽:156
線性表有哪兩種存儲結構 發布:2025-02-01 07:30:04 瀏覽:216
坡向壓縮機 發布:2025-02-01 07:09:10 瀏覽:410
夏新手機初始密碼是什麼 發布:2025-02-01 06:58:23 瀏覽:790
ppt存儲路徑 發布:2025-02-01 06:55:06 瀏覽:115
aspx腳本 發布:2025-02-01 06:44:13 瀏覽:999