天天看點

使用GPUImage實作視訊濾鏡

這裡直接引用官方描述:

the gpuimage framework is a bsd-licensed ios library that lets you apply gpu-accelerated filters and other effects to images, live camera video, and movies. in comparison to core image (part of ios 5.0), gpuimage allows you to write your own custom filters, supports deployment to ios 4.0, and has a simpler interface. however, it currently lacks some of the more advanced features of core image, such as facial detection.

<a href="https://github.com/bradlarson/gpuimage">項目位址:https://github.com/bradlarson/gpuimage</a>

濾鏡處理的原理就是把靜态圖檔或者視訊的每一幀進行圖形變換再顯示出來。它的本質就是像素點的坐标和顔色變化,這點從gpuimage項目中濾鏡的源代碼就可以了解到。

例如下面就是一個名為darkenblend的濾鏡代碼:

<code>uniform sampler2d inputimagetexture; uniform sampler2d inputimagetexture2;</code>

<code></code>

<code>void main() {</code>

<code>} );</code>

gpuimage的最新版本已經内置了125個濾鏡。也支援編寫自定義濾鏡(custom filter)。

資料源需要實作gpuimageoutput接口,而後續各個環節(包括最後處理輸出結果)的對象都要實作gpuimageinput接口。每個處理環節都是從上一個環節擷取圖像資料,進行處理後再将結果傳遞給下一個。下遊的處理對象稱為上一步的target。使用addtarget:方法為處理鍊路添加每個環節的對象。一個常見的鍊條如下:

資料源(例如gpuimagevideocamera或者gpuimagemovie)-&gt;各類filter-&gt;gpuimageview

如果需要将結果輸出到檔案,隻要把上述流程中最末的gpuimageview改為一個gpuimagemoviewriter即可。是以濾鏡的添加和替換,以及輸出結果都十分簡單友善。

附一張gpuimage的結構圖

使用GPUImage實作視訊濾鏡

将濾鏡接入app非常簡單,隻要建立一個gpuimagemovie,一個具體的gpuimagefilter和一個用來顯示的gpuimageview,然後按處理鍊條的上下遊關系把它們用addtarget串起來。

下面附上我的app裡面的調用代碼(預覽視訊):

然後就是一些重要的參數設定:

playatactualspeed

控制gpuimageview預覽視訊時的速度是否要保持真實的速度。如果設為no,則會将視訊的所有幀無間隔渲染,導緻速度非常快。設為yes,則會根據視訊本身時長計算出每幀的時間間隔,然後每渲染一幀,就sleep一個時間間隔,進而達到正常的播放速度。

shouldrepeat

控制視訊是否循環播放。

當你不想預覽,而是想将處理過的結果輸出到檔案時,步驟也類似,隻是不再需要建立gpuimageview,而是需要一個gpuimagemoviewriter:

1.預覽時不支援播放聲音

視訊結果輸出到gpuimageview預覽時不支援播放聲音,是以要自行添加聲音播放:

自行建立了一個播放器對象

<code>(void) setupsound { if (theaudioplayer != nil) {</code>

<code>} theaudioplayer = [[avplayer alloc] initwithurl:self.url]; }</code>

跟gpuimageview的圖像同步播放

由于gpuimagemovie裡面沒有在這幾個重要位置提供回調,是以隻能在源代碼中直接添加,這也導緻了對源碼的侵入,不利于以後版本更新。

2.gpuimageview預覽視訊并循環播放時,當播放重新開始時,有大約50%的機率會有紅屏閃一下,目前還未定位到原因

3.gpuimageview預覽視訊時,app切到背景會crash,是以要特别處理下,在willdisappear和handleapplicationwillenterbackgroundnotify這兩個時機都要暫停濾鏡處理:

對應的,在willappear和handleapplicationwillenterforegroundnotify這兩個時機要重新開機處理:

下一篇: git工具

繼續閱讀