sci9
sci9

Reputation: 776

Generate an Image of a sloped sinewave

How we can generate the following grayscale image in Python?

The following code generates horizontal pattern, but I need a sloped one.

import numpy as np
import matplotlib.pyplot as plt

N = 256
x = np.linspace(-np.pi,np.pi, N)
sine1D = 128.0 + (127.0 * np.sin(x * 8.0))
sine1D = np.uint8(sine1D)
sine2D = np.tile(sine1D, (N,1))
print(sine2D.shape)
plt.imshow(sine2D, cmap='gray')

enter image description here

Upvotes: 3

Views: 2557

Answers (2)

yacola
yacola

Reputation: 3013

In response to your comment below @Patrick Artner's answer:

As we can see numpy.roll cannot generate a smooth pattern

The function np.roll is not responsible for the smoothness of the resulting image, it's the function plt.imshow. You need to tell it how to properly interpolate the generated data. So just by specifying the interpolation keyword argument to the function call, you may have for instance:

plt.imshow(sine2D,interpolation='bilinear', cmap='gray')

which leads to a smoother result:

smooth_roll

but there are plenty of other possibilities : 'bicubic', 'spline16', 'spline36'...

Upvotes: 2

Patrick Artner
Patrick Artner

Reputation: 51643

You can use numpy.roll to shift your 1D sine data around:

import numpy as np
import matplotlib.pyplot as plt

N = 256
x = np.linspace(-np.pi,np.pi, N)
sine1D = 128.0 + (127.0 * np.sin(x * 8.0))
sine1D = np.uint8(sine1D)
sine2D = np.ndarray((N,N), dtype=np.uint8)
for i in range(N):
    sine2D[i]= np.roll(sine1D,-i)  # shift the 1D sin data by -i, -i increases with rows
plt.imshow(sine2D, cmap='gray')
plt.show()

Output:

resulting image

If you roll your 1D data you'll get the desired slanted pattern. If you want a special slanted angle you would have to roll more/less then 1 per advacing row to get it flatter/steeper.

Documentation:

Upvotes: 3

Related Questions