How to use image jpg with numpy.load() - numpy

I try to implement this code, using colab:
x = np.load('data_sample.npy',allow_pickle=True)
stacked_x = np.concatenate([x,x,x],1)
stacked_x.shape
but my sample was an image in jpg format, so I wasn't able to convert these images to .npy to use it.
actually, I tried this code:
import numpy as np
array = np.asarray('image.JPG')
print(array.tobytes())
print(array)
x = np.load(array,allow_pickle=True)
stacked_x = np.concatenate([x,x,x],1)
stacked_x.shape
print(x)
but I got:
and when I use this code :
x = np.load(array.tobytes(),allow_pickle=True)
I got:
so, any suggestion to solve this, precisely to convert .jpg to .npy?

Look at what your code does:
In [57]: np.asarray('image.JPG')
Out[57]: array('image.JPG', dtype='<U9')
In [58]: np.asarray('image.JPG').tobytes()
Out[58]: b'i\x00\x00\x00m\x00\x00\x00a\x00\x00\x00g\x00\x00\x00e\x00\x00\x00.\x00\x00\x00J\x00\x00\x00P\x00\x00\x00G\x00\x00\x00'
That's just playing with the string. It's not doing anything with a file named "image.JPG". You need to use some sort of image processing package to first load the file, converting it from the compressed format to a 3d array.
np.load is used to load a file that was created by np.save('file.npy'). It doesn't make sense to give that array variable as the file name. It won't load a jpg file.
np.load('file.npy',allow_pickle=True)

Related

Is there a way to convert numpy array to PNG/JPG... payload without saving it as a file?

Suppose there exists a numpy array, data. I am trying to do the equivalent of the following
cv2.imwrite(filename, data)
with open(filename, 'rb') as fp:
data_compressed = filename.read()
without having to write to a file. Is there a way to convert numpy array to its equivalent PNG/JPG... representation without having to write to a file and read it as binary?
As Miki pointed out, imencode(...) is the solution.

Code for changing multiple .img files into .png, then into numpy array

I'm doing a convolutional neural network classification and currently all my tiles are in .img format (thanks ArcMap). I know I need to get them in .png format, but haven't found code that could convert a whole folder of them. Is that doable?
Eventually I also need to get all those .pngs into a numpy array. I found basic code that will do it for just .png, but is there a way to convert the whole folder at once?
Thanks everyone!
Yes it is doable, just use Python Pil! and loop over all files in the folder with glob.
Some example code:
import os
from PIL import Image
import glob
counter = 0
for image in glob.glob("/Users/Testfolder/*.jpg"):
counter = counter + 1
img = Image.open(image)
img.save('/Users/Testfolder/' + (str(counter)+'img.png'))

Convert np.array of PIL image to binary

Im trying to convert the numpy array of the PIL image I got to a binary one but anything I have tried doesn't work.
this is what I got so far:
from PIL import Image
import numpy as np
pixels=np.array(Image.open("covid_encrypted_new.png").getdata())
def to_bin(pixels):
return [format(i,"08b") for i in pixels]
also when I tried to iterate over the array and change each value to type bin it also didnt go well for me.
What else can I try?
thanks
This could be what your looking for
Ori here: How to read the file and convert it to a binary image in Python
# Read Image
img= Image.open(file_path)
# Convert Image to Numpy as array
img = np.array(img)
# Put threshold to make it binary
binarr = np.where(img>128, 255, 0)
# Covert numpy array back to image
binimg = Image.fromarray(binarr)
You could even use opencv to convert
img = np.array(Image.open(file_path))
_, bin_img = cv2. threshold(img,127,255,cv2.THRESH_BINARY)

How to parse mxnet params file into plain text?

I'm trying to use Python to parse mxnet params into plain text. The code looks like the below. But the parsing result is not plain string, but some encoded text looks like this, "... \xaa>\x0f\xed\x8e>\xaf!\x8f>g ..." Could anybody give me some tips on it? Thanks a lot!
...
param_file = 'resnet-50-0000.params'
with open(param_file, 'rb') as f:
net_params = f.read()
...
The parameters are binary files. If you want to read them as plain text you need to decode them first as a dictionary of parameter_name->NDArray, that you can convert them to numpy. From numpy you can convert it to a list and then process it as a list (of lists) of scalar.
import mxnet as mx
params = mx.nd.load('resnet-50-0000.params')
for k, param in params.items():
print(k)
print(param.asnumpy().tolist())

How to get the Numpy array of file stream of any image

I'm trying to use the imageai python library, and more particularly this function:
detector.detectObjectsFromImage()
The doc says it should be used with a Numpy array of file stream of any image.
https://imageai.readthedocs.io/en/latest/detection/index.html
When I pass it a Numpy array, like this:
detections = detector.detectObjectsFromImage(input_image=anumpyarray,input_type = "array")
I get the error:
detections =
detector.detectObjectsFromImage(input_image=anumpyarray,input_type =
"array") File
"/usr/local/lib/python3.6/site-packages/imageai/Detection/init.py",
line 517, in detectObjectsFromImage raise ValueError("Ensure you
specified correct input image, input type, output type and/or output
image path ") ValueError: Ensure you specified correct input image,
input type, output type and/or output image path
Is it because a Numpy array and a Numpy array of a stream of an image are different things?
I know it's old, but for anyone who needs help:
Try to set 2 additional params:
minimum_percentage_probability=0, output_type='array'
For more info, go into imageai\Detection\__init__.py -> detectObjectsFromImage