HarmonyOS實(shí)現(xiàn)簡單的圖像識別
源碼下載地址
https://gitee.com/Shadows1946397262/brunhild_-harmony-os/tree/master/Brunhild_HarmonyOS/North_Samples/Image_Recognition
開發(fā)環(huán)境要求
- DevEco Studio版本:DevEco Studio 3.1 Release
- HarmonyOS SDK版本:API version 9
工程要求
- API9
- Stage模型
正文
最近鄰分類器簡介
下面是關(guān)于最近鄰分類器的一個簡單例子:
假設(shè)在傳送帶上有兩種魚,分別是鱸魚(seabass)和鮭魚(salmon)。現(xiàn)在我們需要用光學(xué)傳感器對傳送帶上的魚按品種進(jìn)行分類,因此需要設(shè)計(jì)一個分類器,不妨設(shè)計(jì)一個最近鄰分類器。假如我們只考慮魚的兩個特征——寬度和魚身的亮度,現(xiàn)在我們選取十條鱸魚和十條鮭魚進(jìn)行特征提取,并建立一個平面直角坐標(biāo)系(y軸用于表示寬度特征的數(shù)值,x軸用于表示亮度特征的數(shù)值,這樣就構(gòu)成了一個二維特征空間),再將每條魚的由其寬度值和亮度值確定的坐標(biāo)在圖中顯示出來。
圖中,紅色點(diǎn)代表鮭魚樣本的特征向量,藍(lán)色點(diǎn)代表鱸魚樣本的特征向量,它們都屬于被訓(xùn)練的數(shù)據(jù)。當(dāng)檢測設(shè)備獲取了某條品種未知的魚的亮度特征和寬度特征時(shí),最近鄰分類器所要做的是:先將此品種未知的魚的亮度值和寬度值表示成特征空間上的向量P,然后計(jì)算向量P與每個已訓(xùn)練樣本向量的距離。其中,距離采用歐式范數(shù),在二維空間中計(jì)算公式為:
由于先前已訓(xùn)練了20項(xiàng)數(shù)據(jù),所以我們可以獲取20項(xiàng)距離數(shù)據(jù),將它們表示為d1, d2, ... ,d20。接著,分類器通過逐項(xiàng)比較獲取最小距離di(i∈[1,20]∩N),這意味著第i個已訓(xùn)練樣本是未知品種的魚的最近鄰。因此,當(dāng)?shù)趇個已訓(xùn)練樣本屬于鱸魚品種時(shí),上述品種未知的魚將被分類為鱸魚,否則分類為鮭魚。
基于最近鄰分類器的圖像識別算法
找出被測樣本的最近鄰后,我們便可以憑借此最近鄰進(jìn)行圖片分類。
代碼結(jié)構(gòu)
─entry/src/main
├─ module.json5
├─ resources
│ ├─ zh_CN
│ ├─ rawfile
│ │ ├─ p1.png
│ │ ├─ p2.png
│ │ ├─ p3.png
│ │ ├─ p4.png
│ │ ├─ p5.png
│ │ ├─ p6.png
│ │ ├─ s1.png
│ │ └─ s2.png
│ ├─ en_US
│ └─ base
└─ ets
├─ XL_Modules
│ └─ XL_Image_NNC.ts
├─ pages
│ └─ Index.ets
└─ entryability
└─ EntryAbility.ts
圖片解碼流程
在本案例中,不論是用于訓(xùn)練分類器的圖片還是待檢測的圖片,都需要提前放入Demo
的rawfile目錄下的。如果要獲取某個圖像資源,我們只需要知道此圖像的名稱(字符串?dāng)?shù)據(jù)),然后通過資源管理者模塊resourceManager即可取得。如下給出以獲取rawfile目錄下名為'p1.png',大小為100px乘100px的圖片資源為例,需要編寫的相關(guān)操作語句。
獲取resourceManager:
let context = getContext(this)
const resourceMgr = context.resourceManager
獲取rawfile文件夾下p1.png的ArrayBuffer:
let Data = await resourceMgr.getRawFileContent('test.jpg')
let buffer = Data.buffer
創(chuàng)建ImageSource實(shí)例:
const imageSource = image.createImageSource(buffer)
創(chuàng)建PixelMap實(shí)例:
const pixelMap = await imageSource.createPixelMap();
因?yàn)槲覀冃枰鰣D像處理,所以還需要創(chuàng)建一個ArrayBuffer實(shí)例(buffer對象),并讀取PixelMap實(shí)例的數(shù)據(jù)至buffer中。這樣以后,buffer就是一個儲存了p1.png圖像數(shù)據(jù)的BGRA_8888格式的數(shù)組(也可以稱之為向量)了。
let dim = 100*100*4 //維度
let buffer = new ArrayBuffer(dim)
await pixelMap.readPixelsToBuffer(buffer)
.catch(err => {
console.error(`err: +${err}`)
})
由于buffer是BGRA_8888格式的數(shù)組,所以buffer中第i,i+1,i+2, i+3(i∈[0,dim/4-1])分別代表某個像素點(diǎn)藍(lán)色分量(B),綠色分量(G),紅色分量(R)和透明度分量(A)。因?yàn)楸景咐膱D像識別是在灰度圖的基礎(chǔ)上進(jìn)行的,所以我們還需要將BGRA_8888格式的數(shù)組轉(zhuǎn)化為灰度值數(shù)組。
RGB圖轉(zhuǎn)灰度圖并不難,只需要將每個像素點(diǎn)的藍(lán)色,綠色和紅色分量加權(quán)求和,就可以得到每個像素點(diǎn)的灰度值。其中,灰度值 = (紅色通道值 * 0.299) + (綠色通道值 * 0.587) + (藍(lán)色通道值 * 0.114)。這里的加權(quán)系數(shù)是根據(jù)人眼對不同顏色敏感度的差異來確定的。
關(guān)鍵代碼
XL_Image_NNC.ts
import image from '@ohos.multimedia.image';
import common from '@ohos.app.ability.common';
//所操作圖片的尺寸(圖片的寬高一致)
const OPERATION_SIZE = 100
/*
* 函數(shù)名: Get_NumberType_Array_MinValue_Index
* 描述: 返回輸入的number型Array中數(shù)值最小的元素所在索引
*/
function Get_NumberType_Array_MinValue_Index(arr:Array<number>):number{
let location:number = 0
for(var i = 0; i < arr.length; ++i){
if(arr[i]<arr[location]){
location = i
}
}
return location
}
//最近鄰分類器能力接口
interface I_Nearest_Neighbor_Classifier{
train(context:common.Context,Train_Data:Array<string>)
identify(test_data:string)
}
/*
* 類名: XL_Image_NNC
* 描述: 基于最近鄰分類器的圖像識別模塊
*/
class XL_Image_NNC implements I_Nearest_Neighbor_Classifier{
//日志標(biāo)簽
private TAG:string = '------[XL_Image_NNC] '
//BGRA_8888圖對應(yīng)向量的規(guī)模
private dim_rgb:number = 4*(OPERATION_SIZE**2)
//灰度圖對應(yīng)向量的規(guī)模
private dim_gray:number = OPERATION_SIZE**2
//RGB圖向量轉(zhuǎn)化為灰度圖向量時(shí), 三原色(red green blue)通道值各自占灰度值的權(quán)重, 并且滿足R_Weight + G_Weight + B_Weight = 1
private R_Weight:number = 0.299
private G_Weight:number = 0.587
private B_Weight:number = 0.114
//已加入的圖像向量的集合(BGRA_8888)
private Trained_Data_RGB:Array<Uint8Array> = []
//已加入的圖像向量的集合(灰度圖)
private Trained_Data_Gray:Array<Uint8Array> = []
//存儲距離(歐式范數(shù))的數(shù)組
private Distance_Array:Array<number> = []
//儲存資源管理模塊的變量
private resourceMgr = null
/*
* 方法名: train
* 描述: 為分類器填充數(shù)據(jù), 使得分類器獲取監(jiān)督模式識別的功能
* 參數(shù): context: UIAbility的上下文對象 Train_Data: 待訓(xùn)練的圖片集(圖片需要提前儲存在rawfile目錄下)
*/
public async train(context:common.Context,Train_Data:Array<string>) {
//通過context獲取ResourceManager(資源管理模塊)
this.resourceMgr = context.resourceManager
//遍歷和處理待輸入的圖片數(shù)據(jù)
for (var item of Train_Data) {
//通過resourceMgr的getRawFileContent方法(填入圖片的文件名字符串),獲取rawfile目錄下某個圖片所資源對應(yīng)的UintArray
let rawData = await this.resourceMgr.getRawFileContent(item)
//通過先前獲取的UintArray創(chuàng)建ImageSource實(shí)例
let imageSource = image.createImageSource(rawData.buffer)
//通過ImageSource實(shí)例創(chuàng)建像素表
let pixelMap = await imageSource.createPixelMap()
//將像素表讀取到新建的ArrayBuffer變量中
let buffer = new ArrayBuffer(this.dim_rgb)
await pixelMap.readPixelsToBuffer(buffer)
.catch(err => {
console.error(this.TAG+`err: +${err}`)
})
//最后將ArrayBuffer攜帶的RGB型圖像向量存入Trained_Data_RGB(向量集合)中
this.Trained_Data_RGB.push(new Uint8Array(buffer))
}
//將獲取的RGB型圖像向量集合轉(zhuǎn)化為灰度型圖像向量集合
for(var element of this.Trained_Data_RGB){
let GrayScaleVector = new Uint8Array(this.dim_gray)
let index:number = 0
//遍歷RGB型圖像向量的元素
for(var i = 0; i < element.length; i++){
if((i+1)%4 == 0){
//獲取像素點(diǎn)的R,G,B通道值, 將他們加權(quán)求和得到灰度值
var grayScale = this.R_Weight*element[i-3]+this.G_Weight*element[i-2]+this.B_Weight*element[i-1]
//存儲
GrayScaleVector[index++] = grayScale
}
}
//最后將GrayScaleVector攜帶的灰度型圖像向量存入Trained_Data_Gray(向量集合)中
this.Trained_Data_Gray.push(GrayScaleVector)
}
}
/*
* 方法名: identify
* 描述: 基于已獲取的數(shù)據(jù),完成監(jiān)督模式識別,返回輸入樣本的最近鄰在Trained_Data_Gray中的索引
* 參數(shù): test_data: 待識別的圖片(圖片需要儲存在rawfile目錄下)
*/
public async identify(test_data:string):Promise<number>{
//排除異常情況
if(this.resourceMgr == null){
console.error(this.TAG+'Please train the image data before identifying')
return -1
}
//獲取rawfile目錄下某個圖片所對應(yīng)的UintArray
let rawData = await this.resourceMgr.getRawFileContent(test_data)
//通過先前獲取的UintArray創(chuàng)建ImageSource實(shí)例
let imageSource = image.createImageSource(rawData.buffer)
//通過ImageSource實(shí)例創(chuàng)建像素表
let pixelMap = await imageSource.createPixelMap()
//將像素表讀取到新建的buffer變量中
let buffer = new ArrayBuffer(this.dim_rgb)
await pixelMap.readPixelsToBuffer(buffer)
.catch(err => {
console.error(this.TAG+`err: +${err}`)
})
let Sample_RGB = new Uint8Array(buffer)
let Sample_Gray = new Uint8Array(this.dim_gray)
let index:number = 0
//將RGB型的圖像向量轉(zhuǎn)化為灰度型的圖像向量
for(var i = 0; i < Sample_RGB.length; i++){
if((i+1)%4 == 0){
var grayScale = this.R_Weight*Sample_RGB[i-3]+this.G_Weight*Sample_RGB[i-2]+this.B_Weight*Sample_RGB[i-1]
Sample_Gray[index++] = grayScale
}
}
//賦初值
this.Distance_Array = []
//計(jì)算待檢測圖像向量與每項(xiàng)已訓(xùn)練圖片向量在高維空間的的距離(距離采用歐式范數(shù)), 即(Σ(A[i] - B[i]))^0.5, i ∈ [0, dim_gray) ∩ N
for(var item of this.Trained_Data_Gray){
var distance:number = 0
//計(jì)算dim_gray維向量空間上樣本與已訓(xùn)練數(shù)據(jù)的距離(歐式范數(shù))
for(var i = 0; i < this.dim_gray; i++){
distance += (Sample_Gray[i]-item[i])**2
}
distance = distance**0.5
this.Distance_Array.push(distance)
console.info(this.TAG+'distance: '+distance)
}
//獲取Distance_Array中最小元素所在索引并輸出, 此索引即為樣本的最近鄰在Trained_Data_Gray中的索引
return Get_NumberType_Array_MinValue_Index(this.Distance_Array)
}
}
//導(dǎo)出本模塊
export default new XL_Image_NNC()
同往期一樣,筆者青睞于將新開發(fā)的功能集成到一個ts文件里并導(dǎo)出,以方便管理與維護(hù)。在本模塊中,功能被集成在類XL_Image_NNC中,其中,train方法用于為分類器訓(xùn)練數(shù)據(jù)(雖然不涉及迭代的過程,姑且將其稱為"訓(xùn)練"吧),identify方法則是基于已訓(xùn)練的數(shù)據(jù)進(jìn)行圖像分類。