Search code examples
pythonmatplotlibimage-processingmesh

Scattering a mesh grid over a grayscale image


I'm trying to create a numpy mesh grid according to a grayscale image. For example, considering this image

Geometry figure

I want to scatter points to get something similar to

Scattered points

in cartesian coordinates. Is there any library for doing such a task or I need to implement something from scratch? Thanks in advance, I will appreciate any help.


Solution

  • Guessing somewhat as to what you mean, here is an approach:

    • load image as greyscale
    • threshold to pure black and white
    • get coordinates of all black pixels
    • randomly subsample 0.5% of the coordinates
    • create empty output image
    • draw white circles on output image's alpha channel at the subsampled locations which will make the black background become visible at those locations

    #!/usr/bin/env python3
    
    import numpy as np
    import cv2 as cv
    
    # Load image as greyscale
    im = cv.imread('Gkzaa.png', cv.IMREAD_GRAYSCALE)
    
    # Otsu threshold to pure black and pure white, i.e. 0 or 255
    _, thresh = cv.threshold(im, 0, 255, cv.THRESH_BINARY+cv.THRESH_OTSU)
    
    # Get X and Y coordinates of all black pixels
    Y, X = np.where(thresh==0)
    nBlack = len(Y)
    
    # Get indices of 0.5% of those black pixels
    indices = np.random.choice(nBlack, size=int(nBlack*0.005), replace=False)
    
    # Form an empty (black) output image and an alpha channel for it
    BGR = np.zeros((*im.shape,3), np.uint8)
    A   = np.zeros_like(im)
    
    # Draw circles of opacity into the alpha channel at selected indices
    for i in indices:
        cv.circle(A, center=(X[i], Y[i]), radius=4, color=255, thickness=cv.FILLED)
    
    # Stack the alpha channel onto the BGR channel to make BGRA and save
    res = np.dstack((BGR,A))
    cv.imwrite('result.png', res)
    

    enter image description here