边缘检测,肖像胶卷色彩cameo.py/filters.py/utils.py文件内容,基于python2.7,IDE:spyder

filters.py

# -*- coding: utf-8 -*-
"""
Created on Sat Mar 17 12:55:25 2018


@author: 423
"""


import cv2
import numpy as np
import utils 


class VConvolutionFilter(object):
    def __init__(self, kernel):
        self._kernel = kernel


    def apply(self, src, dst):
        cv2.filter2D(src, -1, self._kernel, dst)


# 特定的锐化滤波器
class SharpenFilter(VConvolutionFilter):
    def __init__(self):
        kernel = np.array([[-1, -1, -1],
                           [-1, 9, -1],
                           [-1, -1, -1]])
        VConvolutionFilter.__init__(self, kernel)




# 边缘检测滤波器
class FindEdgesFilter(VConvolutionFilter):
    def __init__(self):
        kernel = np.array([[-1, -1, -1],
                           [-1, 8, -1],
                           [-1, -1, -1]])
        VConvolutionFilter.__init__(self, kernel)




# 模糊滤波器
class BlurFilter(VConvolutionFilter):
    def __init__(self):
        kernel = np.array([[0.04, 0.04, 0.04, 0.04, 0.04],
                           [0.04, 0.04, 0.04, 0.04, 0.04],
                           [0.04, 0.04, 0.04, 0.04, 0.04],
                           [0.04, 0.04, 0.04, 0.04, 0.04],
                           [0.04, 0.04, 0.04, 0.04, 0.04]])
        VConvolutionFilter.__init__(self, kernel)




# 脊状和浮雕效果
class EmbossFilter(VConvolutionFilter):
    def __init__(self):
        kernel = np.array([[-2, -1, 0],
                           [-1, 1, 1],
                           [0, 1, 2]])
        VConvolutionFilter.__init__(self, kernel)


class BGRFuncFilter(object):


    def __init__(self, vFunc = None, bFunc = None, gFunc = None, rFunc = None,dtype = np.uint8) :


        length = np.iinfo(dtype).max + 1
        self._bLookupArray = utils.createLookupArray(utils.createCompositeFunc(bFunc, vFunc), length)
        self._gLookupArray = utils.createLookupArray(utils.createCompositeFunc(gFunc, vFunc), length)
        self._rLookupArray = utils.createLookupArray(utils.createCompositeFunc(rFunc, vFunc), length)


    def apply(self, src, dst) :


        """Apply the filter with a BGR source/destination."""
        b, g, r = cv2.split(src)
        utils.applyLookupArray(self._bLookupArray, b, b)
        utils.applyLookupArray(self._gLookupArray, g, g)
        utils.applyLookupArray(self._rLookupArray, r, r)
        cv2.merge([ b, g, r ], dst)






class BGRCurveFilter(BGRFuncFilter):


    def __init__(self, vPoints = None, bPoints = None,gPoints = None, rPoints = None, dtype = np.uint8):
        BGRFuncFilter.__init__(self, utils.createCurveFunc(vPoints), utils.createCurveFunc(bPoints), utils.createCurveFunc(gPoints), utils.createCurveFunc(rPoints), dtype)


class BGRPortraCurveFilter(BGRCurveFilter):
    def __init__(self, dtype = np.uint8):
        BGRCurveFilter.__init__(
            self,
            vPoints = [ (0, 0), (23, 20), (157, 173), (255, 255) ],
            bPoints = [ (0, 0), (41, 46), (231, 228), (255, 255) ],
            gPoints = [ (0, 0), (52, 47), (189, 196), (255, 255) ],
            rPoints = [ (0, 0), (69, 69), (213, 218), (255, 255) ],
            dtype = dtype)

        
def strokeEdges(src,
                dst,
                blurKsize=7,#中值滤波ksize
                edgeKsize=5):#Laplacian算子ksize
    if blurKsize>=3:
        #中值滤波
        blurredSrc=cv2.medianBlur(src,blurKsize)
        #修改为灰度颜色空间
        graySrc=cv2.cvtColor(blurredSrc,cv2.COLOR_BGR2GRAY)
    else:
        graySrc=cv2.cvtColor(src,cv2.COLOR_BGR2GRAY)
    cv2.Laplacian(graySrc,cv2.CV_8U,graySrc,ksize=edgeKsize)
    normalizedInverseAlpha=(1.0/255)*(255-graySrc)
    channels=cv2.split(src)
    for channel in channels:
        channel[:]=channel*normalizedInverseAlpha

    cv2.merge(channels,dst)



utils.py

# -*- coding: utf-8 -*-
"""
Created on Sat Mar 17 13:36:24 2018


@author: 423
"""


import cv2
import numpy as np
import scipy.interpolate


def createCurveFunc(points):
    """Return a function derived from control points."""
    if points is None:
        return None
    num_points = len(points)
    if num_points < 2:
        return None
    xs, ys = zip(*points)
    if num_points < 4:
        kind = 'linear'
        # 'quadratic' is not implemented.
    else:
        kind = 'cubic'
    return scipy.interpolate.interp1d(xs, ys, kind,bounds_error = False)

def createLookupArray(func, length = 256):
    """Return a lookup for whole-number inputs to a function. The lookup values are clamped to [0, length - 1]."""
    if func is None:
        return None
    lookup_array = np.empty(length)
    i = 0
    while i < length:
        func_i = func(i)
        lookup_array[i] = min(max(0, func_i), length - 1)
        i += 1
    return lookup_array

def applyLookupArray(lookup_array, src, dst):
    """Map a source to a destination using a lookup."""
    if lookup_array is None:
        return
    dst[:] = lookup_array[src]


def createCompositeFunc(func0, func1):
    """Return a composite of two functions."""
    if func0 is None:
        return func1
    if func1 is None:
        return func0
    return lambda x: func0(func1(x))


def createFlatView(array):
    """Return a 1D view of an array of any dimensionality."""
    flat_view = array.view()
    flat_view.shape = array.size

    return flat_view


cameo.py

# -*- coding: utf-8 -*-
"""
Created on Sat Mar 17 12:36:14 2018


@author: 423
"""


import cv2
from managers import WindowManager,CaptureManager
import filters


class Cameo(object):


    def __init__(self):
        self._windowManager=WindowManager('Cameo',self.onkeypress)
        self._captureManager=CaptureManager(cv2.VideoCapture(0),self._windowManager,True)
        self._curveFilter = filters.BGRPortraCurveFilter()
        
    def run(self):
        self._windowManager.createWindow()
        while self._windowManager.isWindowCreated:
            self._captureManager.enterFrame()
            frame=self._captureManager.frame


            filters.strokeEdges(frame, frame)
            self._curveFilter.apply(frame, frame)


            self._captureManager.exitFrame()
            self._windowManager.processEvents()


    def onkeypress(self,keycode):
        '''
            space-> 载图
            tab->启动和停止视频录制
            esc->退出应用


        :param keycode:
        :return:
        '''
        if keycode==32:#space
            self._captureManager.writeImage('screenshot.png')
        elif keycode==9:#tab
            if not self._captureManager.isWritingVideo:
                self._captureManager.startWritingVideo('screencast.avi')
            else:
                self._captureManager.stopWritingVideo()
        elif keycode==27:#esc
            self._windowManager.destroyWindow()
if __name__=='__main__':
    Cameo().run()

你可能感兴趣的:(边缘检测,肖像胶卷色彩cameo.py/filters.py/utils.py文件内容,基于python2.7,IDE:spyder)