I have an array of pixel values from a greyscale image. I want to export these values into a text file or CSV. I have been trying to to this using various function including: xlsxwrite, write, CSV but I have so far been unsuccessful in doing this. This is what I am working with:
from PIL import Image
import numpy as np
import sys
# load the original image
img_file = Image.open("seismic.png")
img_file.show()
# get original image parameters...
width, height = img_file.size
format = img_file.format
mode = img_file.mode
# Make image Greyscale
img_grey = img_file.convert('L')
img_grey.save('result.png')
img_grey.show()
# Save Greyscale values
value = img_grey.load()
Essentially I would like to save 'value' to use elsewhere.
Instead of using the .load() method, you could use this (with 'x' as your grey-scale image):
value = np.asarray(x.getdata(),dtype=np.float64).reshape((x.size[1],x.size[0]))
This is from: Converting an RGB image to grayscale and manipulating the pixel data in python
Once you have done this, it is straightforward to save the array on file using numpy.savetxt
numpy.savetxt("img_pixels.csv", value, delimiter=',')
Note: x.load() yields an instance of a Pixel Access class which cannot be manipulated using the csv writers you mentioned. The methods available for extracting and manipulating individual pixels in a Pixel Access class can be found here: http://pillow.readthedocs.io/en/3.1.x/reference/PixelAccess.html
Related
I have a MR image volume in *.mhd format, and I do not have access to the original DICOM file. The image is not square and I need to crop the image and save a new *.mhd file again. I have a *.json file which contains all information of the original DICOM header.
Can anyone help me here?
Here's a example that shows how to crop an image in SimpleITK to get a square sub-image:
import random
import SimpleITK as sitk
img = sitk.Image(random.randrange(100,200), random.randrange(100,200), sitk.sitkUInt8)
size = img.GetSize()
print(size)
min_size = min(size[0], size[1])
# using python slicing to extract a sub-image
cropped_img = img[0:min_size, 0:min_size]
print(cropped_img.GetSize())
sitk.WriteImage(cropped_img, "square.mhd")
Note that the section being cropped is at the "end" (high index values) of the image.
I have a large set of photos that when stitched together constitute a map . I need to write a small code that goes through the images, reads the coordinates( latitude, longitude ) and saves them in four files.
photo that expalins how I want the 1000 photo (1 map) to be saved in four files according to their location
I was able to figure out how to read a single image coordinates using python
pip install exif
from exif import Image
img_path = 'images/image_exif.jpg'
with open(img_path, 'rb') as src: # open(filename, mode).
img = Image(src)
print (src.name, img)
import PIL
from PIL import Image
image = PIL.Image.open('images/image_exif.jpg')
img.gps_longitude
so what I want to do now, is itterate through all the images to find the the two axes and then find which images lay in the first quarter, save them in a file, which in the second, save them in another file.....etc
I tried to find the highest long and lat, so that then I find the min long and lat, in order to find the midpoint
source_path = r"C:\Users\q\Pictures\Test"
for i in source_path:
max(i.gps_longitude)
But I got the following error : str' object has no attribute 'gps_longitude'
I am trying to change the values from a gray scale PNG image and then create an image from those changed values.
The first step I took was using a python implementation of libpng.
With that I was able to get a list of all the pixel values of the PNG. It is a gray scale image so the values where from 0 to 100. I do a quick algorithm to change the values. And then I try to create it into a new PNG file. Its all on a single line so I use regex to format it into a 2D array.
I attempted to use this that I found here
from PIL import Image
import numpy as np
pixels = [[100,0,0],[0,100,0],[0,0,100]]
# Convert the pixels into an array using numpy
array = np.array(pixels)
print(array)
# Use PIL to create an image from the new array of pixels
new_image = Image.fromarray(array, 'L')
new_image.save('testing.png')
But I guess the formatting that PIL uses is different from what the libpng is so instead of making an image that looks like 3 white pixels diagonally, I only get 1 white pixel on the top left. So either I change the values I am getting from libpng so that numpy works, or I find something in libpng that will allow me to change the values directly and create the new file.
The error in your code is that you are not setting the right data type for the array. If you call array = np.array(pixels, dtype='uint8') then your code will work.
I have a data set of images in an image processing project. I want to input an image and scan through the data set to recognize the given image. What module/ library/ approach( eg: ML) should I use to identify my image in my python- opencv code?
To find exactly the same image, you don't need any kind of ML. The image is just an array of pixels, so you can check if the array of the input image equals that of an image in your dataset.
import glob
import cv2
import numpy as np
# Read in source image (the one you want to match to others in the dataset)
source = cv2.imread('test.jpg')
# Make a list of all the images in the dataset (I assume they are images in a directory)
filelist = glob.glob(r'C:\Users\...\Images\*.JPG')
# Loop through the images, read them in and check if an image is equal to your source
for file in filelist:
img = cv2.imread(file)
if np.array_equal(source, img):
print("%s is the same image as source" %(file))
break
I have a list called w (size: 784), which I outputted to a png greyscale image:
import matplotlib.pyplot as plt
tmp = 1/(1+np.exp(-10*w/w.max()))
plt.imshow(tmp.reshape(28,28),cmap="gray")
plt.draw()
plt.savefig("final_weight_vector")
Now I want to read the png image back to be a vector.
The solutions I found so far:
First:
import matplotlib.image as mpimg
img=mpimg.imread('final_weight_vector.png')
but img appears to not be greyscale, because its dimensions turend out to be (600, 800, 4).
Second:
reading the file as RGB and converting to greyscale:
im = Image.open('final_weight_vector.png').convert('LA')
However, I couldn't find how to iterate over im so I have no idea as to what's inside. Further, I am not sure the output of im will have the exact same values as the original w.
Help please?
The problem is that what you saved is probably a plot of the 28x28 image, not the image itself.
To be sure, please preview the image. I bet it is 600x800, not 28x28. I also suppose it contains many additional elements, like axes and padding.
If you want to store your array in a loadable format, you may use numpy.save() (and numpy.load() to load it).
You may also use PIL to save your array as image (e.g. using something similar to: http://code.activestate.com/recipes/577591-conversion-of-pil-image-and-numpy-array/)