pythonnumpyopencv

How to generate an array which is a multiple of original?


I'm trying to upsize OpenCV images in Python in such a manner that the individual pixels are spread out by an integral factor; I use this to visually examine deep detail and individual pixel values can be seen (using cv2.imshow in this instance).

For example, an array:

    [[1,2],
     [3,4]]

And a factor of 2 means I'd get:

    [[1,1,2,2],
     [1,1,2,2],
     [3,3,4,4], 
     [3,3,4,4]]

I've done this by generating an array of size*factor using np.zeros, then iterating each point in the original array and copying it to the target array using (for example)

for y in range(src.shape[0]):
    for x in range(src.shape[1]):
        tgt[y*f:y*f+f, x*f:x*f+f, :] = src[y,x,:]

But as you can imagine, it's not the fastest approach, and I'm hoping I'm just not finding the right thing.

OpenCV (and PIL) do not have a resize capability that doesn't interpolate by one method or another, which seems weird all by itself.

I looked over & tried numpy broadcast*, numpy stride_trickks, opencv functions, PIL functions.

The semi-manual method works as long as I don't need interactivity, but I'm trying to adjust parameters to several opencv functions quickly so I can find the right combinations to solve my problem. (Which is proprietary, so I can't share imagery...) Waiting a significant time between results is counterproductive.


Solution

  • You can use opencv's cv.resize with nearest-neighbor as interpolation method (cv.INTER_NEAREST) to achieve what you need:

    import cv2 as cv
    import numpy as np
    
    src = np.array([[1,2], [3,4]])
    dst = cv.resize(src, (4,4), interpolation=cv.INTER_NEAREST)
    print(dst)
    

    Output:

    [[1 1 2 2]
     [1 1 2 2]
     [3 3 4 4]
     [3 3 4 4]]
    

    Live demo