简体   繁体   中英

Python distort image with repeating edges using numpy.roll()

I have an image as a numpy array with (w,h,3) which I want to distort along the y axis using some values that were generated using overlaying sine waves.

Below is the code of the method and 3 images (input, current output, desired output). The desired output was done using the Photoshop Wave Distort filter which has an option to repeat the edge pixels. Basicly I want to implement that option to repeat the edge pixels instead of wrapping the pixels around so that the image looks more like a path.

Another thing is that I don't think np.roll() is the right method for the job but I'm a total noob with anything numpy-related.

def distortH(data, distortions, w, h):
    imgdata = np.zeros((h, w, 3), dtype=np.uint8)
    for y in range(h):
        imgdata[y] = np.roll(data[y], distortions[y], axis=0)
    return imgdata
  • data: numpy array with w,h,3

  • distortions: array that has the length of h with the distortion values between -500 and 500 (in this case; distortion values will have different scalings dependent on the image size)

  • w: width of the image

  • h: height of the image

Thanks in advance!

Input: 输入图像

Current Output 电流输出

Desired Output 期望的输出

Solved!

numpy.roll() was indeed not the right method.

Solved it using numpy.pad()

def distortH(data, distortions, w, h):
    imgdata = np.zeros((h, w, 3), dtype=np.uint8)
    for y in range(h):
        if distortions[y] == 0:
            imgdata[y] = data[y]
        elif distortions[y] > 0:
            ndata = np.pad(data[y], ((distortions[y], 0),(0,0)), mode='edge')
            imgdata[y] = ndata[:len(ndata)-distortions[y], :]
        else:
            ndata = np.pad(data[y], ((0, -distortions[y]),(0,0)), mode='edge')
            imgdata[y] = ndata[-distortions[y]:, :]
    return imgdata

Might not be the most optimal way of solving it. But it's way faster than going through all the lines manually and swapping the pixels one by one.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM