2017-02-02 42 views
0

與simpleVideoFilter和人臉檢測類似,我想用彩色矩形突出顯示我的GPUImage2視頻源的一部分。 SolidColorGenerator似乎是一個很好的開始,但有兩個例外。首先,我不確定如何將SolidColorGenerator輸出轉置到原始圖像的正確位置。其次,我不確定如何將N個矩形添加到我的原始圖像。同時,我已經與LineGenerator取得了成功,但我認爲矩形看起來會更好。GPUImage2使用SolidColorGenerator作爲RectangleGenerator

獎勵: 帶圓角和單個像素邊框的矩形。

enter image description here

回答

0

什麼工作,我正在寫一RectangleGenerator。新的RectangleGenerator的關鍵是繪製GL_TRIANGLES。這可以作出

glDrawArrays(GLenum(GL_TRIANGLES), 0, GLsizei(positions.count) * 2) 

一種優化是使用GL_Elements和GL_TRIANGLE_STRIP,雖然我沒能明白這一點。

enter image description here

完整的解決方案應該支持的邊框,邊框寬度和cornerRadius。現在簡單的矩形就足夠了。下面的完整代碼。

let vertex = "attribute vec4 position; void main(){ gl_Position = position; }" 

let fragment = "uniform lowp vec3 fillColor; void main(){ gl_FragColor = vec4(fillColor, 1.0); }" 

public class RectangleGenerator: ImageGenerator { 

let rectangleShader:ShaderProgram 
var uniformSettings = ShaderUniformSettings() 

public var fillColor:Color = Color.green { didSet { uniformSettings["fillColor"] = fillColor } } 

public override init(size:Size) { 
    rectangleShader = crashOnShaderCompileFailure("RectangleGenerator"){try sharedImageProcessingContext.programForVertexShader(vertex, fragmentShader:fragment)} 
    super.init(size:size) 

    ({fillColor = Color.green})() 
} 

public func renderRectangles(_ positions:[Position]) { 
    guard positions.count > 3 else { return } 

    imageFramebuffer.activateFramebufferForRendering() 

    rectangleShader.use() 
    uniformSettings.restoreShaderSettings(rectangleShader) 
    clearFramebufferWithColor(Color.transparent) 

    guard let positionAttribute = rectangleShader.attributeIndex("position") else { fatalError("A position attribute was missing from the shader program during rendering.") } 

    let convertedPositions = positions.flatMap{$0.toGLArray()} 
    glVertexAttribPointer(positionAttribute, 2, GLenum(GL_FLOAT), 0, 0, convertedPositions) 

    glBlendEquation(GLenum(GL_FUNC_ADD)) 
    glBlendFunc(GLenum(GL_ONE), GLenum(GL_ONE)) 
    glEnable(GLenum(GL_BLEND)) 

    glDrawArrays(GLenum(GL_TRIANGLES), 0, GLsizei(positions.count) * 2) 
    glDisable(GLenum(GL_BLEND)) 

    notifyTargets() 
} 
} 

快樂編碼