Python Numpy,mask圖像的生成詳解
在numpy中,有一個(gè)模塊叫做ma,這個(gè)模塊幾乎復(fù)制了numpy里面的所有函數(shù),當(dāng)然底層里面都換成了對(duì)自己定義的新的數(shù)據(jù)類型MaskedArray的操作。
我們來(lái)看最基本的array定義。
An array class with possibly masked values. Masked values of True exclude the corresponding element from any computation.
MaskedArray是一個(gè)可能帶有掩膜信息的數(shù)組,對(duì)于它的任何計(jì)算都是只針對(duì)掩膜值為True的數(shù)值上的。
Construction::
x = MaskedArray(data, mask=nomask, dtype=None, copy=False, subok=True,
ndmin=0, fill_value=None, keep_mask=True, hard_mask=None,
shrink=True, order=None)
這個(gè)class的屬性有很多,但是呢,我們只需要關(guān)注三個(gè)屬性就好了,也就是data,mask和fill_value。其他的屬性很難用到,舉個(gè)例子,比如那個(gè)hard_mask,這個(gè)屬性為True就是指data一旦某些值被掩蓋掉了就真的丟失了。詳細(xì)的可以看源碼注解。這里不過(guò)多介紹。
Parameters ---------- data : array_like Input data. mask : sequence, optional Mask. Must be convertible to an array of booleans with the same shape as `data`. True indicates a masked (i.e. invalid) data. fill_value : scalar, optional Value used to fill in the masked values when necessary. If None, a default based on the data-type is used.
data就不多說(shuō)了,一個(gè)array_like,tuple,list,ndarray都行。
mask是一個(gè)只包含True和False的ndarray,它的shape和data一致,這個(gè)數(shù)組是讓你指定需要掩蓋的值的,標(biāo)記為True的數(shù)據(jù)會(huì)被掩蓋掉。被掩蓋的位置會(huì)變成 –(這是兩個(gè)短橫杠,類型是MaskedConstant )
fill_value是一個(gè)標(biāo)量,當(dāng)你掩蓋掉一些值之后,如果你想把這些被掩蓋的值換成另外一個(gè)值,那么你就需要用到它。
import numpy.ma as npm import numpy as np data = np.random.randint(1, 10, size=[1, 5, 5]) mask = data < 5 arr = npm.array(data, mask=mask) print(arr) #[[[6 6 -- 8 --] # [-- -- -- 6 7] # [9 -- -- 6 9] # [-- -- 5 -- 8] # [6 9 -- 5 --]]]
不過(guò)numpy也可以直接對(duì)ndarray進(jìn)行條件運(yùn)算。
import numpy as np arr = np.random.randint(1, 10, size=[1, 5, 5]) mask = arr<5 arr[mask] = 0 # 把標(biāo)記為True的值記為0 print(arr) #[[[9 9 7 6 0] # [0 0 6 9 0] # [8 0 8 5 0] # [0 5 5 8 9] # [0 7 0 0 6]]]
以上這篇Python Numpy, mask圖像的生成詳解就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
Python實(shí)現(xiàn)簡(jiǎn)單的"導(dǎo)彈" 自動(dòng)追蹤原理解析
這篇文章主要介紹了Python實(shí)現(xiàn)簡(jiǎn)單的"導(dǎo)彈" 自動(dòng)追蹤原理解析,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-03-03
Django搭建MySQL主從實(shí)現(xiàn)讀寫分離
本文主要介紹了Django搭建MySQL主從實(shí)現(xiàn)讀寫分離,文中通過(guò)示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-08-08
在jupyter notebook中使用pytorch的方法
這篇文章主要介紹了在jupyter notebook中使用pytorch的方法,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-09-09
淺談python中的@以及@在tensorflow中的作用說(shuō)明
這篇文章主要介紹了淺談python中的@以及@在tensorflow中的作用說(shuō)明,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2021-03-03
Tensorflow實(shí)現(xiàn)將標(biāo)簽變?yōu)閛ne-hot形式
這篇文章主要介紹了Tensorflow實(shí)現(xiàn)將標(biāo)簽變?yōu)閛ne-hot形式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-05-05
Python稀疏矩陣及參數(shù)保存代碼實(shí)現(xiàn)
這篇文章主要介紹了Python稀疏矩陣及參數(shù)保存代碼實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-04-04

