def main():
    displayer = Displayer()

    A = cv2.cvtColor(fetch_image('apple.jpg'), cv2.COLOR_BGR2RGB)
    B = cv2.cvtColor(fetch_image('orange.jpg'), cv2.COLOR_BGR2RGB)

    # generate Gaussian pyramid for A
    G = A.copy()
    gpA = [G]
    for i in xrange(6):
        G = cv2.pyrDown(G)
        gpA.append(G)

    # generate Gaussian pyramid for B
    G = B.copy()
    gpB = [G]
    for i in xrange(6):
        G = cv2.pyrDown(G)
        gpB.append(G)

    # generate Laplacian Pyramid for A
    lpA = [gpA[5]]
    for i in xrange(5, 0, -1):
        GE = cv2.pyrUp(gpA[i])
        L = cv2.subtract(gpA[i - 1], GE)
        lpA.append(L)

    # generate Laplacian Pyramid for B
    lpB = [gpB[5]]
    for i in xrange(5, 0, -1):
        GE = cv2.pyrUp(gpB[i])
        L = cv2.subtract(gpB[i - 1], GE)
        lpB.append(L)

    # Now add left and right halves of images in each level
    LS = []
    for la, lb in zip(lpA, lpB):
        rows, cols, dpt = la.shape
        ls = np.hstack((la[:, 0:cols / 2], lb[:, cols / 2:]))
        LS.append(ls)

    # now reconstruct
    ls_ = LS[0]
    for i in xrange(1, 6):
        ls_ = cv2.pyrUp(ls_)
        displayer.add_image(ls_, i)
        ls_ = cv2.add(ls_, LS[i])

    # image with direct connecting each half
    real = np.hstack((A[:, :cols / 2], B[:, cols / 2:]))

    displayer.add_image(ls_, "pyramid")
    #displayer.add_image(real, "stacked")

    #for i in range(len(lpA)):
    #    displayer.add_image(LS[i], i)

    displayer.display()
def main():
    displayer = Displayer()

    A = cv2.cvtColor(fetch_image('apple.jpg'), cv2.COLOR_BGR2RGB)
    B = cv2.cvtColor(fetch_image('orange.jpg'), cv2.COLOR_BGR2RGB)

    # generate Gaussian pyramid for A
    G = A.copy()
    gpA = [G]
    for i in xrange(6):
        G = cv2.pyrDown(G)
        gpA.append(G)

    # generate Gaussian pyramid for B
    G = B.copy()
    gpB = [G]
    for i in xrange(6):
        G = cv2.pyrDown(G)
        gpB.append(G)

    # generate Laplacian Pyramid for A
    lpA = [gpA[5]]
    for i in xrange(5,0,-1):
        GE = cv2.pyrUp(gpA[i])
        L = cv2.subtract(gpA[i-1],GE)
        lpA.append(L)

    # generate Laplacian Pyramid for B
    lpB = [gpB[5]]
    for i in xrange(5,0,-1):
        GE = cv2.pyrUp(gpB[i])
        L = cv2.subtract(gpB[i-1],GE)
        lpB.append(L)

    # Now add left and right halves of images in each level
    LS = []
    for la,lb in zip(lpA,lpB):
        rows,cols,dpt = la.shape
        ls = np.hstack((la[:,0:cols/2], lb[:,cols/2:]))
        LS.append(ls)

    # now reconstruct
    ls_ = LS[0]
    for i in xrange(1,6):
        ls_ = cv2.pyrUp(ls_)
        displayer.add_image(ls_, i)
        ls_ = cv2.add(ls_, LS[i])

    # image with direct connecting each half
    real = np.hstack((A[:,:cols/2],B[:,cols/2:]))

    displayer.add_image(ls_, "pyramid")
    #displayer.add_image(real, "stacked")

    #for i in range(len(lpA)):
    #    displayer.add_image(LS[i], i)

    displayer.display()
Beispiel #3
0
def main():
    img = fetch_image('zebra-black-and-white.jpg', 0)

    # global thresholding
    ret1, th1 = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)

    # Otsu's thresholding
    ret2, th2 = cv2.threshold(img, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)

    # Otsu's thresholding after Gaussian filtering
    blur = cv2.GaussianBlur(img, (5, 5), 0)
    ret3, th3 = cv2.threshold(blur, 0, 255,
                              cv2.THRESH_BINARY + cv2.THRESH_OTSU)

    # plot all the images and their histograms
    images = [img, 0, th1, img, 0, th2, blur, 0, th3]
    titles = [
        'Original Noisy Image', 'Histogram', 'Global Thresholding (v=127)',
        'Original Noisy Image', 'Histogram', "Otsu's Thresholding",
        'Gaussian filtered Image', 'Histogram', "Otsu's Thresholding"
    ]

    for i in xrange(3):
        plt.subplot(3, 3, i * 3 + 1), plt.imshow(images[i * 3], 'gray')
        plt.title(titles[i * 3]), plt.xticks([]), plt.yticks([])
        plt.subplot(3, 3, i * 3 + 2), plt.hist(images[i * 3].ravel(), 256)
        plt.title(titles[i * 3 + 1]), plt.xticks([]), plt.yticks([])
        plt.subplot(3, 3, i * 3 + 3), plt.imshow(images[i * 3 + 2], 'gray')
        plt.title(titles[i * 3 + 2]), plt.xticks([]), plt.yticks([])
    plt.show()
def main():
    displayer = Displayer()

    orig = fetch_image(sys.argv[1], 0)
    displayer.add_image(orig, 'Original')

    square = np.ones((9, 9), np.float32)
    rectangle = cv2.getStructuringElement(cv2.MORPH_RECT, (1, 13))
    ellipse = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))
    cross = cv2.getStructuringElement(cv2.MORPH_CROSS, (5, 5))
    kernel = cross

    displayer.add_image(cv2.erode(orig, kernel, iterations=1), 'Erosion')
    displayer.add_image(cv2.dilate(orig, kernel, iterations=1), 'Dilation')
    displayer.add_image(cv2.morphologyEx(orig, cv2.MORPH_OPEN, kernel),
                        'Opening')
    closing = cv2.morphologyEx(orig, cv2.MORPH_CLOSE, kernel)
    displayer.add_image(closing, 'Closing')
    displayer.add_image(cv2.morphologyEx(closing, cv2.MORPH_OPEN, kernel),
                        'OpeningClosing')
    displayer.add_image(cv2.morphologyEx(orig, cv2.MORPH_GRADIENT, kernel),
                        'Gradient')
    displayer.add_image(cv2.morphologyEx(orig, cv2.MORPH_TOPHAT, kernel),
                        'Top Hat')
    displayer.add_image(cv2.morphologyEx(orig, cv2.MORPH_BLACKHAT, kernel),
                        'Black Hat')

    displayer.display(cmap='gray')
Beispiel #5
0
def main():
    img = fetch_image('zebra-black-and-white.jpg',0)

    # global thresholding
    ret1,th1 = cv2.threshold(img,127,255,cv2.THRESH_BINARY)

    # Otsu's thresholding
    ret2,th2 = cv2.threshold(img,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)

    # Otsu's thresholding after Gaussian filtering
    blur = cv2.GaussianBlur(img,(5,5),0)
    ret3,th3 = cv2.threshold(blur,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)

    # plot all the images and their histograms
    images = [img, 0, th1,
              img, 0, th2,
              blur, 0, th3]
    titles = ['Original Noisy Image','Histogram','Global Thresholding (v=127)',
              'Original Noisy Image','Histogram',"Otsu's Thresholding",
              'Gaussian filtered Image','Histogram',"Otsu's Thresholding"]

    for i in xrange(3):
        plt.subplot(3,3,i*3+1),plt.imshow(images[i*3],'gray')
        plt.title(titles[i*3]), plt.xticks([]), plt.yticks([])
        plt.subplot(3,3,i*3+2),plt.hist(images[i*3].ravel(),256)
        plt.title(titles[i*3+1]), plt.xticks([]), plt.yticks([])
        plt.subplot(3,3,i*3+3),plt.imshow(images[i*3+2],'gray')
        plt.title(titles[i*3+2]), plt.xticks([]), plt.yticks([])
    plt.show()
Beispiel #6
0
def main():
    img = fetch_image('messi5.jpg')

    res = cv2.resize(img, None, fx=3, fy=2, interpolation=cv2.INTER_CUBIC)

    cv2.imshow('img', res)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
Beispiel #7
0
def main():
    img = fetch_image('messi5.jpg')

    res = cv2.resize(img, None, fx=3, fy=2, interpolation=cv2.INTER_CUBIC)

    cv2.imshow('img', res)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
def main():
    displayer = Displayer()

    orig = cv2.cvtColor(fetch_image(sys.argv[1]), cv2.COLOR_BGR2GRAY)

    displayer.add_image(orig, 'Original')


    img = cv2.bilateralFilter(np.float32(orig), 9, 75, 75)



    x_kernel = np.array([[-1, 0, 1],
                         [-2, 0, 2],
                         [-1, 0, 1]])

    y_kernel = np.array([[ 1,  2,  1],
                         [ 0,  0,  0],
                         [-1, -2, -1]])
    """
    x_kernel = np.array([[3, 10, 3],
                         [0, 0, 0],
                         [-3, -10, -3]])

    y_kernel = np.array([[ -3,  -0,  3],
                         [ -10,  0,  10],
                         [ -3, -0, 3]])
    """

    """
    y_kernel = x_kernel = np.array([[ 0.5, 1, 0.5],
                                    [ 1, -6, 1],
                                    [ 0.5, 1, 0.5]])
    """

    x_gradient = cv2.filter2D(img, -1, x_kernel)
    abs_x = np.absolute(x_gradient)
    x_grad_u8 = np.uint8(abs_x)
    displayer.add_image(x_grad_u8, 'manual x gradient')

    y_gradient = cv2.filter2D(img, -1, y_kernel)
    abs_y = np.absolute(y_gradient)
    y_grad_u8 = np.uint8(abs_y)
    displayer.add_image(y_grad_u8, 'manual y gradient')


    magnitude = cv2.magnitude(abs_x, abs_y)
    magnitude_u8 = np.uint8(magnitude)
    displayer.add_image(magnitude_u8, 'magnitude')
    """
    lap = cv2.Laplacian(orig, -1, cv2.CV_64F)
    displayer.add_image(np.uint8(lap), 'laplacian')
    """
    canny = cv2.Canny(orig, 100, 200)
    displayer.add_image(np.uint8(canny), 'Canny')

    displayer.display(cmap='gray')
Beispiel #9
0
def main():
    img = fetch_image('messi5.jpg', 0)
    rows, cols = img.shape

    M = cv2.getRotationMatrix2D((cols / 2, rows / 2), 90, 1)
    dst = cv2.warpAffine(img, M, (cols, rows))

    cv2.imshow('img', dst)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
def main():
    img = fetch_image('messi5.jpg', 0)
    rows,cols = img.shape

    M = np.float32([[1,0, 0], [0, 1, 0]])
    dst = cv2.warpAffine(img, M, (cols, rows))

    cv2.imshow('img', dst)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
Beispiel #11
0
def main():
    img = fetch_image('messi5.jpg', 0)
    rows, cols = img.shape

    M = np.float32([[1, 0, 0], [0, 1, 0]])
    dst = cv2.warpAffine(img, M, (cols, rows))

    cv2.imshow('img', dst)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
Beispiel #12
0
def main():
    img = fetch_image('messi5.jpg', 0)
    rows,cols = img.shape

    M = cv2.getRotationMatrix2D((cols/2, rows/2), 90, 1)
    dst = cv2.warpAffine(img, M, (cols, rows))

    cv2.imshow('img', dst)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
Beispiel #13
0
def main():
    img = fetch_image('sudokusmall.png')
    rows, cols, ch = img.shape

    pts1 = np.float32([[56, 65], [68, 52], [28, 387], [389, 390]])
    pts2 = np.float32([[0, 0], [40, 0], [0, 300], [300, 300]])

    M = cv2.getPerspectiveTransform(pts1, pts2)

    dst = cv2.warpPerspective(img, M, (300, 300))

    plt.subplot(121), plt.imshow(img), plt.title('Input')
    plt.subplot(122), plt.imshow(dst), plt.title('Output')
    plt.show()
Beispiel #14
0
def main():
    img = fetch_image(sys.argv[1])

    displayer = Displayer()

    kernel = np.ones((5, 5), np.float32)/25

    displayer.add_image(img, 'Original')
    displayer.add_image(cv2.filter2D(img, -1, kernel), 'Average')
    displayer.add_image(cv2.GaussianBlur(img, (5, 5), 0), 'Gaussian')
    displayer.add_image(cv2.medianBlur(img, 5), 'Median')
    displayer.add_image(cv2.bilateralFilter(img, 9, 75, 75), 'Bilateral')

    displayer.display()
def main():
    img = fetch_image("sudokusmall.png")
    rows, cols, ch = img.shape

    pts1 = np.float32([[56, 65], [68, 52], [28, 387], [389, 390]])
    pts2 = np.float32([[0, 0], [40, 0], [0, 300], [300, 300]])

    M = cv2.getPerspectiveTransform(pts1, pts2)

    dst = cv2.warpPerspective(img, M, (300, 300))

    plt.subplot(121), plt.imshow(img), plt.title("Input")
    plt.subplot(122), plt.imshow(dst), plt.title("Output")
    plt.show()
Beispiel #16
0
def main():
    img = fetch_image('drawing.png')
    rows,cols,ch = img.shape


    pts1 = np.float32([[50,50], [200,50], [50, 200]])
    pts2 = np.float32([[10,100], [100, 50], [100, 250]])

    M = cv2.getAffineTransform(pts1, pts2)
    dst = cv2.warpAffine(img, M, (cols, rows))

    plt.subplot(121), plt.imshow(img), plt.title('Input')
    plt.subplot(122), plt.imshow(dst), plt.title('Output')
    plt.show()
def main():
    displayer = Displayer()

    orig = cv2.cvtColor(fetch_image(sys.argv[1]), cv2.COLOR_BGR2GRAY)

    displayer.add_image(orig, 'Original')

    img = cv2.bilateralFilter(np.float32(orig), 9, 75, 75)

    x_kernel = np.array([[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]])

    y_kernel = np.array([[1, 2, 1], [0, 0, 0], [-1, -2, -1]])
    """
    x_kernel = np.array([[3, 10, 3],
                         [0, 0, 0],
                         [-3, -10, -3]])

    y_kernel = np.array([[ -3,  -0,  3],
                         [ -10,  0,  10],
                         [ -3, -0, 3]])
    """
    """
    y_kernel = x_kernel = np.array([[ 0.5, 1, 0.5],
                                    [ 1, -6, 1],
                                    [ 0.5, 1, 0.5]])
    """

    x_gradient = cv2.filter2D(img, -1, x_kernel)
    abs_x = np.absolute(x_gradient)
    x_grad_u8 = np.uint8(abs_x)
    displayer.add_image(x_grad_u8, 'manual x gradient')

    y_gradient = cv2.filter2D(img, -1, y_kernel)
    abs_y = np.absolute(y_gradient)
    y_grad_u8 = np.uint8(abs_y)
    displayer.add_image(y_grad_u8, 'manual y gradient')

    magnitude = cv2.magnitude(abs_x, abs_y)
    magnitude_u8 = np.uint8(magnitude)
    displayer.add_image(magnitude_u8, 'magnitude')
    """
    lap = cv2.Laplacian(orig, -1, cv2.CV_64F)
    displayer.add_image(np.uint8(lap), 'laplacian')
    """
    canny = cv2.Canny(orig, 100, 200)
    displayer.add_image(np.uint8(canny), 'Canny')

    displayer.display(cmap='gray')
Beispiel #18
0
def main():
    img = fetch_image('gradient.png', 0)
    ret,thresh1 = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)
    ret,thresh2 = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY_INV)
    ret,thresh3 = cv2.threshold(img,127,255,cv2.THRESH_TRUNC)
    ret,thresh4 = cv2.threshold(img,127,255,cv2.THRESH_TOZERO)
    ret,thresh5 = cv2.threshold(img,127,255,cv2.THRESH_TOZERO_INV)

    titles = ['Original Image','BINARY','BINARY_INV','TRUNC','TOZERO','TOZERO_INV']
    images = [img, thresh1, thresh2, thresh3, thresh4, thresh5]

    for i in xrange(6):
        plt.subplot(2, 3, i+1), plt.imshow(images[i], 'gray')
        plt.title(titles[i])
        plt.xticks([]),plt.yticks([])

    plt.show()
Beispiel #19
0
def main():
    img = fetch_image('gradient.png', 0)
    ret, thresh1 = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)
    ret, thresh2 = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY_INV)
    ret, thresh3 = cv2.threshold(img, 127, 255, cv2.THRESH_TRUNC)
    ret, thresh4 = cv2.threshold(img, 127, 255, cv2.THRESH_TOZERO)
    ret, thresh5 = cv2.threshold(img, 127, 255, cv2.THRESH_TOZERO_INV)

    titles = [
        'Original Image', 'BINARY', 'BINARY_INV', 'TRUNC', 'TOZERO',
        'TOZERO_INV'
    ]
    images = [img, thresh1, thresh2, thresh3, thresh4, thresh5]

    for i in xrange(6):
        plt.subplot(2, 3, i + 1), plt.imshow(images[i], 'gray')
        plt.title(titles[i])
        plt.xticks([]), plt.yticks([])

    plt.show()
Beispiel #20
0
def main():
    BLUE = [255,0,0]

    img1 = fetch_image('jason_small.png')

    img1[:,:,0], img1[:,:,2] = img1[:,:,2], img1[:,:,0]

    replicate = cv2.copyMakeBorder(img1,10,10,10,10,cv2.BORDER_REPLICATE)
    reflect = cv2.copyMakeBorder(img1,10,10,10,10,cv2.BORDER_REFLECT)
    reflect101 = cv2.copyMakeBorder(img1,10,10,10,10,cv2.BORDER_REFLECT_101)
    wrap = cv2.copyMakeBorder(img1,10,10,10,10,cv2.BORDER_WRAP)
    constant= cv2.copyMakeBorder(img1,10,10,10,10,cv2.BORDER_CONSTANT,value=BLUE)

    plt.subplot(231),plt.imshow(img1,'gray'),plt.title('ORIGINAL')
    plt.subplot(232),plt.imshow(replicate,'gray'),plt.title('REPLICATE')
    plt.subplot(233),plt.imshow(reflect,'gray'),plt.title('REFLECT')
    plt.subplot(234),plt.imshow(reflect101,'gray'),plt.title('REFLECT_101')
    plt.subplot(235),plt.imshow(wrap,'gray'),plt.title('WRAP')
    plt.subplot(236),plt.imshow(constant,'gray'),plt.title('CONSTANT')

    plt.show()
Beispiel #21
0
def main():
    img = fetch_image("adaptive.png", 0)
    img = cv2.medianBlur(img, 5)

    ret, th1 = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)
    th2 = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 13, 2)
    th3 = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 13, 2)

    titles = [
        "Original Image",
        "Global Thresholding (v = 127)",
        "Adaptive Mean Thresholding",
        "Adaptive Gaussian Thresholding",
    ]
    images = [img, th1, th2, th3]

    for i in xrange(4):
        plt.subplot(2, 2, i + 1), plt.imshow(images[i], "gray")
        plt.title(titles[i])
        plt.xticks([]), plt.yticks([])
    plt.show()
Beispiel #22
0
def main():
    img = fetch_image('messi5.jpg')
    cv2.namedWindow('img')

    pixel = img[100, 200]
    print(pixel)

    print(img.shape)

    ball = img[280:340, 330:390]
    img[273:333, 100:160] = ball
    img[:,:,2] -= 5

    cv2.namedWindow('img')

    while(1):
        cv2.imshow('img', img)
        if cv2.waitKey(20) & 0xFF == 27:
            break

    cv2.destroyAllWindows()
Beispiel #23
0
def main():
    img = fetch_image('adaptive.png', 0)
    img = cv2.medianBlur(img, 5)

    ret, th1 = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)
    th2 = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_MEAN_C,
                                cv2.THRESH_BINARY, 13, 2)
    th3 = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
                                cv2.THRESH_BINARY, 13, 2)

    titles = [
        'Original Image', 'Global Thresholding (v = 127)',
        'Adaptive Mean Thresholding', 'Adaptive Gaussian Thresholding'
    ]
    images = [img, th1, th2, th3]

    for i in xrange(4):
        plt.subplot(2, 2, i + 1), plt.imshow(images[i], 'gray')
        plt.title(titles[i])
        plt.xticks([]), plt.yticks([])
    plt.show()
Beispiel #24
0
def main():
    BLUE = [255, 0, 0]

    img1 = fetch_image("jason_small.png")

    img1[:, :, 0], img1[:, :, 2] = img1[:, :, 2], img1[:, :, 0]

    replicate = cv2.copyMakeBorder(img1, 10, 10, 10, 10, cv2.BORDER_REPLICATE)
    reflect = cv2.copyMakeBorder(img1, 10, 10, 10, 10, cv2.BORDER_REFLECT)
    reflect101 = cv2.copyMakeBorder(img1, 10, 10, 10, 10, cv2.BORDER_REFLECT_101)
    wrap = cv2.copyMakeBorder(img1, 10, 10, 10, 10, cv2.BORDER_WRAP)
    constant = cv2.copyMakeBorder(img1, 10, 10, 10, 10, cv2.BORDER_CONSTANT, value=BLUE)

    plt.subplot(231), plt.imshow(img1, "gray"), plt.title("ORIGINAL")
    plt.subplot(232), plt.imshow(replicate, "gray"), plt.title("REPLICATE")
    plt.subplot(233), plt.imshow(reflect, "gray"), plt.title("REFLECT")
    plt.subplot(234), plt.imshow(reflect101, "gray"), plt.title("REFLECT_101")
    plt.subplot(235), plt.imshow(wrap, "gray"), plt.title("WRAP")
    plt.subplot(236), plt.imshow(constant, "gray"), plt.title("CONSTANT")

    plt.show()
def main():
    displayer = Displayer()

    orig = fetch_image(sys.argv[1], 0)
    displayer.add_image(orig, "Original")

    square = np.ones((9, 9), np.float32)
    rectangle = cv2.getStructuringElement(cv2.MORPH_RECT, (1, 13))
    ellipse = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))
    cross = cv2.getStructuringElement(cv2.MORPH_CROSS, (5, 5))
    kernel = cross

    displayer.add_image(cv2.erode(orig, kernel, iterations=1), "Erosion")
    displayer.add_image(cv2.dilate(orig, kernel, iterations=1), "Dilation")
    displayer.add_image(cv2.morphologyEx(orig, cv2.MORPH_OPEN, kernel), "Opening")
    closing = cv2.morphologyEx(orig, cv2.MORPH_CLOSE, kernel)
    displayer.add_image(closing, "Closing")
    displayer.add_image(cv2.morphologyEx(closing, cv2.MORPH_OPEN, kernel), "OpeningClosing")
    displayer.add_image(cv2.morphologyEx(orig, cv2.MORPH_GRADIENT, kernel), "Gradient")
    displayer.add_image(cv2.morphologyEx(orig, cv2.MORPH_TOPHAT, kernel), "Top Hat")
    displayer.add_image(cv2.morphologyEx(orig, cv2.MORPH_BLACKHAT, kernel), "Black Hat")

    displayer.display(cmap="gray")
Beispiel #26
0
def main():
    global mode, drawing
    cap = cv2.VideoCapture(0)

    ret, img = cap.read()
    worm_image = np.zeros(img.shape, img.dtype)

    image_width = len(img[0])
    image_height = len(img)

    def draw_line():
        point_1 = (0, 0)
        point_2 = (511, 511)
        blue = 255
        green = 0
        red = 0
        color = (blue, green, red)
        thickness = 5
        cv2.line(img, point_1, point_2, color, thickness)

    def draw_rectangle():
        point_1 = (384, 0)
        point_2 = (510, 128)
        blue = 0
        green = 255
        red = 0
        color = (blue, green, red)
        thickness = 3
        cv2.rectangle(img, point_1, point_2, color, thickness)

    def bdraw_circle(center):
        radius = 63
        blue = 0
        green = 0
        red = 255
        color = (blue, green, red)
        thickness = -1
        cv2.circle(img, center, radius, color, thickness)

    def draw_ellipse():
        center = (256, 256)
        axes_lengths = (100, 50)
        rotation = 20
        start_angle = 0
        end_angle = 180
        color = 255
        thickness = -1
        cv2.ellipse(img, center, axes_lengths, rotation, start_angle,
                    end_angle, color, thickness)

    def draw_polygon():
        points = np.array([
            [10, 5],
            [20, 30],
            [70, 20],
            [50, 10],
        ], np.int32)
        points = points.reshape((-1, 1, 2))
        closed = True
        blue = 0
        green = 255
        red = 255
        color = (blue, green, red)
        cv2.polylines(img, [points], closed, color)

    def draw_text():
        origin = (10, 500)
        font = cv2.FONT_HERSHEY_SIMPLEX
        font_scale = 4
        color = (255, 255, 255)
        thickness = 2
        line_type = cv2.CV_AA
        cv2.putText(img, 'OpenCV', origin, font, font_scale, color, thickness,
                    line_type)

    draw_line()
    draw_rectangle()
    draw_ellipse()
    draw_text()
    draw_polygon()
    x_0 = 449
    y_0 = 63

    bdraw_circle((x_0, y_0))

    X = 0
    Y = 1

    class Worm(object):
        def __init__(self, image, start, length, cell_size, color, stringy=4):
            self.image = image
            self.x, self.y = start
            self.cells = []
            self.length = length
            self.cell_size = cell_size
            self.color = color
            self.stringy = stringy

            self.x_max = len(image[0]) - cell_size
            self.y_max = len(image) - cell_size

            self.last_change = None

        def valid(self, point):
            x, y = point
            if x < 0 or x > self.x_max:
                return False

            if y < 0 or y > self.y_max:
                return False

            return True

        def random_next(self):
            if len(self.cells) > 0:
                x = self.cells[0][X]
                y = self.cells[0][Y]
            else:
                x = self.x
                y = self.y

            new_point = [x, y]
            position = randint(0, 1)
            change = self.cell_size * choice([-1, 1])
            new_point[position] += change
            if self.valid(new_point):
                self.last_change = (position, change)
                return tuple(new_point)

            return (x, y)

        def next_cell(self):
            """Move either up or down."""

            # prefer previous choice
            if len(self.cells
                   ) > 0 and self.last_change is not None and randint(
                       0, self.stringy) != 0:
                new_point = [self.cells[0][X], self.cells[0][Y]]
                new_point[self.last_change[0]] += self.last_change[1]
                if self.valid(new_point):
                    return tuple(new_point)

            return self.random_next()

        def add_cell(self):
            """Add a new cell at the front."""
            new = self.next_cell()
            self.cells.insert(0, new)
            self.draw_cell(new, self.color)

        def move(self):
            """Add a new cell and remove the oldest cell."""
            new = self.next_cell()
            self.cells.insert(0, new)
            old = self.cells.pop(-1)
            if not old in self.cells:
                self.draw_cell(old, color=(0, 0, 0))
            self.draw_cell(new)

        def draw_cell(self, cell, color=None):
            """Draw a cell."""
            if color is None:
                color is self.color

            point_1 = (cell[X], cell[Y])
            point_2 = (cell[X] + self.cell_size, cell[Y] + self.cell_size)
            cv2.rectangle(self.image, point_1, point_2, color, -1)

        def update(self):
            if len(self.cells) < self.length:
                self.add_cell()
            elif len(self.cells) == 0:
                return

            self.move()

            for cell in self.cells:
                self.draw_cell(cell, self.color)

        def change_length(self, new_length):
            cur_len = len(self.cells)
            if new_length > cur_len:
                for _ in range(new_length - cur_len):
                    self.add_cell()
            elif new_length < self.length:
                for _ in range(cur_len - new_length):
                    cell = self.cells.pop(-1)
                    self.draw_cell(cell, color=(0, 0, 0))
                    if len(self.cells) == 0:
                        self.x, self.y = cell
            self.length = length

        def erase(self):
            for cell in self.cells:
                self.draw_cell(cell, color=(0, 0, 0))

    cv2.imshow('image', img)

    def adjust_worm_count(worm_list, count, length, stringy):
        if len(worm_list) < count:
            for _ in range(count - len(worm_list)):
                worm = Worm(
                    worm_image,
                    (randint(0, image_width), randint(0, image_height)),
                    length,
                    5, (
                        randint(0, 256),
                        randint(0, 256),
                        randint(0, 256),
                    ),
                    stringy=stringy)
                worm_list.append(worm)
                worm.update()
        elif len(worm_list) > count:
            for i in range(len(worm_list) - count):
                worm = worm_list.pop()
                worm.erase()

    def adjust_worm_length(worm_list, length):
        for worm in worm_list:
            worm.change_length(length)

    def adjust_worm_stringy(worm_list, stringy):
        for worm in worm_list:
            worm.stringy = stringy

    def nothing(x):
        pass

    cv2.createTrackbar('count', 'image', 0, 1000, nothing)
    cv2.createTrackbar('length', 'image', 0, 2000, nothing)
    cv2.createTrackbar('stringy', 'image', 0, 1000, nothing)

    worms = []
    old_length = 0
    old_stringy = 0

    def paint(x, y):
        global ix, iy, mode
        if mode == True:
            cv2.rectangle(worm_image, (ix, iy), (x, y), (0, 255, 0), -1)
        else:
            cv2.circle(worm_image, (x, y), 5, (0, 0, 255), -1)

    # mouse callback function
    def draw_circle(event, x, y, flags, param):
        global ix, iy, drawing, mode

        if event == cv2.EVENT_LBUTTONDOWN:
            drawing = True
            ix, iy = x, y
        elif event == cv2.EVENT_MOUSEMOVE:
            if drawing == True:
                paint(x, y)
        elif event == cv2.EVENT_LBUTTONUP:
            drawing = False
            paint(x, y)

    cv2.setMouseCallback('image', draw_circle)

    cap_mode = True

    def masked_add(bg_img, fg_img):
        # create mask and inverse mask of fg
        fg_gray = cv2.cvtColor(fg_img, cv2.COLOR_BGR2GRAY)
        ret, mask = cv2.threshold(fg_gray, 10, 255, cv2.THRESH_BINARY)
        mask_inv = cv2.bitwise_not(mask)

        # black out the area of fg in bg
        bg = cv2.bitwise_and(bg_img, bg_img, mask=mask_inv)

        fg = cv2.bitwise_and(fg_img, fg_img, mask=mask)

        final = cv2.addWeighted(bg_img, 0.3, fg, 0.7, 0)

        final = cv2.add(bg, fg)
        return final

    while True:
        if cap_mode:
            ret, img = cap.read()

        count = cv2.getTrackbarPos('count', 'image')
        length = cv2.getTrackbarPos('length', 'image')
        stringy = cv2.getTrackbarPos('stringy', 'image')

        adjust_worm_count(worms, count, length, stringy)

        if old_length != length:
            adjust_worm_length(worms, length)
            old_length = length

        if old_stringy != stringy:
            adjust_worm_stringy(worms, stringy)
            old_stringy = stringy

        for worm in worms:
            worm.update()

        final_img = masked_add(img, worm_image)

        cv2.imshow('image', final_img)
        k = cv2.waitKey(1) & 0xFF
        if k == ord('m'):
            mode = not mode
        if k == ord('r'):
            img[:, :, :] = fetch_image('domo_kun.jpg')
        if k == ord('p'):
            cap_mode = not cap_mode

    cv2.destroyAllWindows()
Beispiel #27
0
def main():
    global mode, drawing
    cap = cv2.VideoCapture(0)

    ret, img = cap.read()
    worm_image = np.zeros(img.shape, img.dtype)

    image_width = len(img[0])
    image_height = len(img)

    def draw_line():
        point_1 = (0, 0)
        point_2 = (511, 511)
        blue = 255
        green = 0
        red = 0
        color = (blue, green, red)
        thickness = 5
        cv2.line(img, point_1, point_2, color, thickness)


    def draw_rectangle():
        point_1 = (384, 0)
        point_2 = (510, 128)
        blue = 0
        green = 255
        red = 0
        color = (blue, green, red)
        thickness = 3
        cv2.rectangle(img, point_1, point_2, color, thickness)


    def bdraw_circle(center):
        radius = 63
        blue = 0
        green = 0
        red = 255
        color = (blue, green, red)
        thickness = -1
        cv2.circle(img, center, radius, color, thickness)


    def draw_ellipse():
        center = (256, 256)
        axes_lengths = (100, 50)
        rotation = 20 
        start_angle = 0
        end_angle = 180
        color = 255
        thickness = -1
        cv2.ellipse(img, center, axes_lengths, rotation, start_angle,
                    end_angle, color, thickness)


    def draw_polygon():
        points = np.array(
            [
                [10, 5],
                [20, 30],
                [70, 20],
                [50, 10],
            ],
            np.int32
        )
        points = points.reshape((-1, 1, 2))
        closed = True 
        blue = 0
        green = 255
        red = 255
        color = (blue, green, red)
        cv2.polylines(img, [points], closed, color)


    def draw_text():
        origin = (10, 500)
        font = cv2.FONT_HERSHEY_SIMPLEX
        font_scale = 4
        color = (255, 255, 255)
        thickness = 2
        line_type = cv2.CV_AA
        cv2.putText(img, 'OpenCV', origin, font, font_scale,
                    color, thickness, line_type)

    draw_line()
    draw_rectangle()
    draw_ellipse()
    draw_text()
    draw_polygon()
    x_0 = 449
    y_0 = 63

    bdraw_circle((x_0, y_0))

    X = 0
    Y = 1

    class Worm(object):
        def __init__(self, image, start, length,
                     cell_size, color, stringy=4):
            self.image = image
            self.x, self.y = start
            self.cells = []
            self.length = length
            self.cell_size = cell_size
            self.color = color
            self.stringy = stringy

            self.x_max = len(image[0]) - cell_size
            self.y_max = len(image) - cell_size

            self.last_change = None

        def valid(self, point):
            x, y = point
            if x < 0 or x > self.x_max:
                return False

            if y < 0 or y > self.y_max:
                return False

            return True

        def random_next(self):
            if len(self.cells) > 0:
                x = self.cells[0][X]
                y = self.cells[0][Y]
            else:
                x = self.x
                y = self.y

            new_point = [x, y]
            position = randint(0, 1)
            change = self.cell_size * choice([-1, 1])
            new_point[position] += change
            if self.valid(new_point):
                self.last_change = (position, change)
                return tuple(new_point)

            return (x, y)

        def next_cell(self):
            """Move either up or down."""

            # prefer previous choice
            if len(self.cells) > 0 and self.last_change is not None and randint(0, self.stringy) != 0:
                new_point = [self.cells[0][X], self.cells[0][Y]]
                new_point[self.last_change[0]] += self.last_change[1]
                if self.valid(new_point):
                    return tuple(new_point)
            
            return self.random_next()

        def add_cell(self):
            """Add a new cell at the front."""
            new = self.next_cell()
            self.cells.insert(0, new)
            self.draw_cell(new, self.color)

        def move(self):
            """Add a new cell and remove the oldest cell."""
            new = self.next_cell()
            self.cells.insert(0, new)
            old = self.cells.pop(-1)
            if not old in self.cells:
                self.draw_cell(old, color=(0, 0, 0))
            self.draw_cell(new)

        def draw_cell(self, cell, color=None):
            """Draw a cell."""
            if color is None:
                color is self.color

            point_1 = (cell[X], cell[Y])
            point_2 = (cell[X] + self.cell_size, cell[Y] + self.cell_size)
            cv2.rectangle(self.image, point_1, point_2, color, -1)

        def update(self):
            if len(self.cells) < self.length:
                self.add_cell()
            elif len(self.cells) == 0:
                return
            
            self.move()
            
            for cell in self.cells:
                self.draw_cell(cell, self.color)

        def change_length(self, new_length):
            cur_len = len(self.cells)
            if new_length > cur_len:
                for _ in range(new_length - cur_len):
                    self.add_cell()
            elif new_length < self.length:
                for _ in range(cur_len - new_length):
                    cell = self.cells.pop(-1)
                    self.draw_cell(cell, color=(0, 0, 0))
                    if len(self.cells) == 0:
                        self.x, self.y = cell
            self.length = length

        def erase(self):
            for cell in self.cells:
                self.draw_cell(cell, color=(0, 0, 0))



    cv2.imshow('image', img)

    def adjust_worm_count(worm_list, count, length, stringy):
        if len(worm_list) < count:
            for _ in range(count - len(worm_list)):
                worm = Worm(worm_image,
                            (randint(0, image_width), randint(0,image_height)),
                            length, 5, (
                                randint(0, 256),
                                randint(0, 256),
                                randint(0, 256),
                            ),
                        stringy=stringy
                )
                worm_list.append(worm)
                worm.update()
        elif len(worm_list) > count:
            for i in range(len(worm_list) - count):
                worm = worm_list.pop()
                worm.erase()


    def adjust_worm_length(worm_list, length):
        for worm in worm_list:
            worm.change_length(length)

    def adjust_worm_stringy(worm_list, stringy):
        for worm in worm_list:
            worm.stringy = stringy


    def nothing(x):
        pass

    cv2.createTrackbar('count', 'image', 0, 1000, nothing)
    cv2.createTrackbar('length', 'image', 0, 2000, nothing)
    cv2.createTrackbar('stringy', 'image', 0, 1000, nothing)

    worms = []
    old_length = 0
    old_stringy = 0


    def paint(x, y):
        global ix, iy, mode
        if mode == True:
            cv2.rectangle(worm_image, (ix, iy), (x, y), (0, 255, 0), -1)
        else:
            cv2.circle(worm_image, (x, y), 5, (0, 0, 255), -1)

    # mouse callback function
    def draw_circle(event, x, y, flags, param):
        global ix, iy, drawing, mode

        if event == cv2.EVENT_LBUTTONDOWN:
            drawing = True
            ix,iy = x,y
        elif event == cv2.EVENT_MOUSEMOVE:
            if drawing == True:
                paint(x, y)
        elif event == cv2.EVENT_LBUTTONUP:
            drawing = False
            paint(x, y)


    cv2.setMouseCallback('image', draw_circle)

    cap_mode = True

    def masked_add(bg_img, fg_img):
        # create mask and inverse mask of fg
        fg_gray = cv2.cvtColor(fg_img, cv2.COLOR_BGR2GRAY)
        ret, mask = cv2.threshold(fg_gray, 10, 255, cv2.THRESH_BINARY)
        mask_inv = cv2.bitwise_not(mask)

        # black out the area of fg in bg
        bg = cv2.bitwise_and(bg_img, bg_img, mask=mask_inv)

        fg = cv2.bitwise_and(fg_img, fg_img, mask=mask)

        final = cv2.addWeighted(bg_img, 0.3, fg, 0.7, 0)

        final = cv2.add(bg, fg)
        return final


    while True:
        if cap_mode:
            ret, img = cap.read()

        count = cv2.getTrackbarPos('count', 'image')
        length = cv2.getTrackbarPos('length', 'image')
        stringy = cv2.getTrackbarPos('stringy', 'image')

        adjust_worm_count(worms, count, length, stringy)

        if old_length != length:
            adjust_worm_length(worms, length)
            old_length = length

        if old_stringy != stringy:
            adjust_worm_stringy(worms, stringy)
            old_stringy = stringy

        for worm in worms:
            worm.update()

        final_img = masked_add(img, worm_image)

        cv2.imshow('image', final_img)
        k = cv2.waitKey(1) & 0xFF
        if k == ord('m'):
            mode = not mode
        if k == ord('r'):
            img[:,:,:] = fetch_image('domo_kun.jpg')
        if k == ord('p'):
            cap_mode = not cap_mode

    cv2.destroyAllWindows()