Perlin noise in python - python

I have searched everywhere for an answer for this question but no luck. I want to figure out how to take the image generated by python's noise library and export it. does anybody know how?

The GitHub repository for the noise library has an examples folder. One of them is an example of how to generate 2D perlin noise and write it to a file.
If you want more standard file formats, such as a PNG or TIFF, you can use Numpy to create an array and write the perlin noise values to the array, and then save the array as an image file using OpenCV.

Convert your data list to a numpy array then use PIL library to save the numpy array to a grayscale image:
# Install PIL: pip install pillow (probably already installed)
from PIL import Image
import numpy as np
from perlin_noise import PerlinNoise
noise = PerlinNoise(octaves=10, seed=1)
xpix, ypix = 100, 100
pic = [[noise([i/xpix, j/ypix]) for j in range(xpix)] for i in range(ypix)]
image = Image.fromarray(np.array(pic) * 255, 'L')
image.save('output.png')

Related

Matplotlib: How to save an image at full resolution?

I've created a mozaic image, such that a large picture consists of many tiny pictures. I can view this image just fine in the matplotlib viewer and I can zoom in to see all the tiny pictures. But when I save the image, no matter the extension, the image loses the zoom ability such that the tiny images become blurred when zooming in. Is there a way to save the image in full resolution?
I have the image in rgb in a numpy array so if there are other libraries more suitable that would work too.
This should work :
from PIL import Image
Image.fromarray(numpy_img).save("img_path.png")
I think you're being mislead by Windows's Photos Application here, which applies blur automatically if you zoom too much.
The image is being saved correctly with all pixel values by Matplotlib, you can check it by zooming again on the pixels of the loaded image.
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
# save image
array = np.random.random((4000, 4000, 3))
plt.imsave("save.png", array)
# load image
img = mpimg.imread("save.png")
plt.imshow(img)
plt.show()
Another option is the small library that I wrote called numpngw. If the numpy array is, say, img (an array of 8-bit or 16-bit unsigned integers with shape (m, n, 3)), you could use:
from numpngw import write_png
write_png('output.png', img)
(If the array is floating point, you'll have to convert the values to unsigned integers. The PNG file format does not store floating point values.)
You can try imageio library:
https://imageio.readthedocs.io/en/stable/userapi.html#imageio.imwrite
from imageio import imwrite
imwrite("image.png", array)

Resize CSV data using Python and Keras

I have CSV files that I need to feed to a Deep-Learning network. Currently my CSV files are of size 360*480, but the network restricts them to be of size 224*224. I am using Python and Keras for the deep-learning part. So how can I resize the matrices?
I was thinking that since aspect ratio is 3:4, so if I resize them to 224:(224*4/3) = 224:299, and then crop the width of the matrix to 224, it could serve the purpose. But I cannot find a suitable function to do that. Please suggest.
I think you're looking for cv.resize() if you're using images.
If not, try numpy.ndarray.resize()
Image processing
If you want to do nontrivial alterations to the data as images (i.e. interpolating between pixel values, assuming that they represent photographs) then you might want to use proper image processing libraries for that. You'd need to treat them not as raw matrixes (csv of numbers) but convert them to rgb images, do the transformations you desire, and convert them back to a numpy matrix.
OpenCV (https://docs.opencv.org/3.4/da/d6e/tutorial_py_geometric_transformations.html)
or Pillow (https://pillow.readthedocs.io/en/3.1.x/reference/Image.html) might be useful to do that.
I found a short and simple way to solve this. This uses the Python Image Library/Pillow.
import numpy as np
import pylab as pl
from PIL import Image
matrix = np.array(list(csv.reader(open('./path/mat.csv', "r"), delimiter=","))).astype("uint8") #read csv
imgObj = Image.fromarray(matrix) #convert matrix to Image object
resized_imgObj = img.resize((224,224)) #resize Image object
imgObj.show()
resized_imgObj.show()
resized_matrix = np.asarray(img) #convert Image object to matrix
While numpy module also has a resize function, but it is not as useful as the aforementioned way.
When I tried it, the resized matrix had lost all the intricacies and aesthetic aspect of the original matrix. This is probably due to the fact that numpy.ndarray.resize doesn't interpolate and missing entries are filled with zeros.
So, for this case Image.resize() is more useful.
You could also convert the csv file to a list, truncate the list, and then convert the list to a numpy array and then use np.reshape.

Medical imaging (PyRadiomics) with .nii.gz files

I am trying to implement the package:
https://pyradiomics.readthedocs.io/en/latest/usage.html
It looks super simple, but they expect .nrrd files.
My files are .nii.gz. How do I solve this?
Also, have anyone tried to apply PyRadiomics on TCIA data? if so, can I see your github or Jupyter Notebook?
Thanks a lot.
You could turn NII into numpy array firstly and then turn it into NRRD with using:
nrrd and nibabel
import numpy as np
import nibabel as nib
import nrrd
# Download NII
example_filename = "image.nii.gz"
image = nib.load(example_filename)
# Turn into numpy array
array = np.array(img.dataobj)
# Save NRRD
nrrd_path_to = "image.nrrd"
nrrd.write(image_path_to, array)
Although the examples are in .nrrd, PyRadiomics uses SimpleITK for image operations. This allows PyRadiomics to support a whole range of image formats, including .nii.gz. You don't have to convert them.
The DWIConverter converts diffusion-weighted MR images in DICOM series into nrrd format for analysis in Slicer. It parses the DICOM header to extract necessary information about measurement frame, diffusion weighting directions, b-values, etc, and write out a nrrd image. For non-diffusion weighted DICOM images, it loads in an entire DICOM series and writes out a single DICOM volume in a .nhdr/.raw pair.
So that trying to convert your .nii.gz inside DICOM files for the nrrd format is a possibility by using this tools. Also, you can look at the SlicerDMRI that is a similar module.

Opening Images as Arrays

I have a script that should open an image as a 2D array but I can't seem to make it work. I have tried using the numpy an PIL libraries. I tried this on different computers. The issue is that it opens the image as a 2D array on one computer but opens them ups as objects on a different compute running the same version of python.
The code that should open the image and store it as an array can be seen below:
img = np.array(Image.open(imagePath))
On one computer I get an array but on another one I get an image object like this:
array(<PIL.TiffImagePlugin.TiffImageFile image mode=I;16B size=320x240 at 0x2289FA8>, dtype=object)
Have you tried the imread function from matplotlib?
from matplotlib.image import imread
image = imread(image_path)
Returns a numpy array and works fine for me (python 3.4).

What is the difference between a PIL Image from PIL.Image.open and a NumPy Image matplotlib.image.imread ?

I would like to know why I should or shouldn't use a matplotlib image over a PIL image. I know that matplotlib uses PIL to load any image that is not a PNG, but what is the advantage in having it in a numpy array over the PIL backend representation?
The PIL API includes function for performing a wide range of image manipulations. But of course, it does not provide a function for all conceivable operations. Numpy is useful when you have a mathematical operation to perform on the image which is not built into the PIL API. PIL has a way of altering pixels one-by-one but because if its reliance on Python loops it can be a very slow way to manipulate a large image (or many images).
Numpy math is relatively fast and it has an expressive syntax which
can make coding new image manipulations easier. Moreover, scipy has many additional image manipulating functions which can be applied to numpy arrays.
Here are a few examples:
emboss
converting rgb to hsv
replacing a color

Categories