Why is imread returning NULL? - python

I am trying to import an images dataset to test_image variable. I'd like to try this way because in my opinion it looks better. But I am getting this error:
(build-in function imread() returned NULL
import cv2 as cv
import os
test_images_path = './test_images/'
test_image = [cv.imread(os.path.join(test_images_path, image) for image in os.listdir(test_images_path))]

Closing parenthesis of cv.imread() was at the wrong place:
import cv2 as cv
import os
test_images_path = './test_images/'
test_images = [cv2.imread(os.path.join(test_images_path, image)) for image in os.listdir(test_images_path)]
for img in test_images:
cv2.imshow('img', img)
cv2.waitKey(0)

I think u have not clearly specified the path from where u are trying to fetch image is plz make sure u saved the image in same location where ur python file is saved

Related

Converting Tiff file to JPG or Png python

Hi i am trying to convert the Tiff file into png or jpg file but the ouput that i am getting is noisy and not what i expected. Below is the code that i have tried :
from PIL import Image
im = Image.open('/content/img.tif')
import numpy as np
imarray = np.array(im)
print(imarray)
from matplotlib import pyplot as plt
plt.imshow(imarray, interpolation='nearest')
plt.show() # To see how the tiff file looks like
import cv2
from PIL import Image, ImageOps
img = (np.maximum(imarray, 0) / imarray.max()) * 255.0
print(img)
img = 255 - img #Inverting the pixel
print("********************************************************************")
print(img)
img = Image.fromarray(np.uint8(img))
img.save(f'/content/img.png')
please find the sample tiff file here
https://drive.google.com/file/d/1Gfyo4dCo_4pfYvUn6_a6lD0SfxZOzUwK/view?usp=sharing
Output png/jpg image i was getting is this
Can anyone please help me in converting the tiff into jpg or png
Thanks
The code below worked for me to read .tiff image and save layers as .jpeg:
from PIL import Image, ImageSequence
#open tiff image
im = Image.open("YOUR IMAGE PATH")
#navigate to the folder were the layers are going to be saved
%cd YOUR DIRECTORY
#loop over layers and export jpeg instances
for i, page in enumerate(ImageSequence.Iterator(im)):
page.mode = 'I'
page.point(lambda i:i*(1./256)).convert('L').save(str(i)+'.jpeg')

How to Image.open a RAW (CR2) file in python?

I have the following code for a .tif file:
img = Image.open("randompic.tif")
image = Jpeg()
image.encodeRGB("randompic.tif")
print(np.array_equal(image.total_bit_objects, np.asarray(Image.open('randompic.tif').convert('L'))))
I try to adapt it for a .CR2 file :
img = np.fromfile('IMG_4387.CR2', "uint16")
image = Jpeg()
image.encodeRGB("IMG_4387.CR2")
print(np.array_equal(image.total_bit_objects, np.asarray(Image.open('IMG_4387.CR2').convert('L'))))
However, Image.open('IMG_4387.CR2') does not work.
Do you have any idea to fix me ?
Why not try the following code. It uses simple PIL
I tried rawpy and rawkit and they had complications with Libraw.
Rawpy worked but performed a postprocessing I could not seem to understand
from PIL import Image
im = Image.open("File.CR2")
rgb_im = im.convert('RGB')
rgb_im.save('File.JPG')

What is wrong in this code as it is not giving output picture?

The code is not giving the output picture
import numpy as np
import cv2 as cv
img = cv.imread('Picture1.jpg',0)
cv.imshow('image',img)
cv.waitKey(0)
cv.imwrite('Picture1.jpg',img)
cv.destroyAllWindows()
Make sure that the Picture1.jpg file is in the same directory as the python file you are running.
Or try calling startWindowThread():
import numpy as np
import cv2 as cv
img = cv.imread('Picture1.jpg',0)
cv.startWindowThread()
cv.imshow('image',img)
cv.waitKey(0)
cv.imwrite('Picture1.jpg',img)
cv.destroyAllWindows()

How can I convert some png files to a video using OpenCV?

The file appears and when I open it it just closes. I'm on Linux Mint Cinnamon.
import cv2
import numpy as np
import glob
size = (500,500)
img_array = []
for filename in glob.glob('home/user/Desktop/Images/*.png'):
img = cv2.imread(filename)
height, width, layers = img.shape
size = (width,height)
img_array.append(img)
out = cv2.VideoWriter('project.avi',cv2.VideoWriter_fourcc(*'DIVX'), 15, size)
for i in range(len(img_array)):
out.write(img_array[i])
out.release()
cvWaitKey(0)
Your code is fundamentally correct, but openCV video writing seems to be very sensitive to the machine environment, codecs etc.
As an alternative, you might consider the imageio library, for example:
import imageio
writer = imageio.get_writer('movie.mp4')
for img in img_array:
writer.append_data(img)
writer.close()
The examples are here.
Typo error: cvWaitKey(0) to cv2.waitKey(0)

Read a base 64 encoded image from memory using OpenCv python library

I'm working on an app that to do some facial recognition from a webcam stream. I get base64 encoded data uri's of the canvas and want to use it to do something like this:
cv2.imshow('image',img)
The data URI looks something like this:
data:image/gif;base64,R0lGODlhEAAQAMQAAORHHOVSKudfOulrSOp3WOyDZu6QdvCchPGolfO0o/XBs/fNwfjZ0frl3/zy7////wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAkAABAALAAAAAAQABAAAAVVICSOZGlCQAosJ6mu7fiyZeKqNKToQGDsM8hBADgUXoGAiqhSvp5QAnQKGIgUhwFUYLCVDFCrKUE1lBavAViFIDlTImbKC5Gm2hB0SlBCBMQiB0UjIQA7
So, for clarity I've shown what the image looks like so the base64 string is not broken.
<img src="data:image/gif;base64,R0lGODlhEAAQAMQAAORHHOVSKudfOulrSOp3WOyDZu6QdvCchPGolfO0o/XBs/fNwfjZ0frl3/zy7////wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAkAABAALAAAAAAQABAAAAVVICSOZGlCQAosJ6mu7fiyZeKqNKToQGDsM8hBADgUXoGAiqhSvp5QAnQKGIgUhwFUYLCVDFCrKUE1lBavAViFIDlTImbKC5Gm2hB0SlBCBMQiB0UjIQA7">
The official doc says, that imread accepts a file path as the argument. From this SO answer, if I do something like:
import base64
imgdata = base64.b64decode(imgstring) #I use imgdata as this variable itself in references below
filename = 'some_image.jpg'
with open(filename, 'wb') as f:
f.write(imgdata)
The above code snippet works and the image file gets generated properly. However I don't think so many File IO operations are feasible considering I'd be doing this for every frame of the stream. I want to be able to read the image into the memory directly creating the img object.
I have tried two solutions that seem to be working for some people.
Using PIL reference:
pilImage = Image.open(StringIO(imgdata))
npImage = np.array(pilImage)
matImage = cv.fromarray(npImage)
I get cv not defined as I have openCV3 installed which is available to me as cv2 module. I tried img = cv2.imdecode(npImage,0), this returns nothing.
Getting the bytes from decoded string and converting it into an numpy array of sorts
file_bytes = numpy.asarray(bytearray(imgdata), dtype=numpy.uint8)
img = cv2.imdecode(file_bytes, 0) #Here as well I get returned nothing
The documentation doesn't really mention what the imdecode function returns. However, from the errors that I encountered, I guess it is expecting a numpy array or a scalar as the first argument. How do I get a handle on that image in memory so that I can do cv2.imshow('image',img) and all kinds of cool stuff thereafter.
I hope I was able to make myself clear.
This is my solution for python 3.7 and without using PIL
import base64
def readb64(uri):
encoded_data = uri.split(',')[1]
nparr = np.fromstring(base64.b64decode(encoded_data), np.uint8)
img = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
return img
i hope that this solutions works for all
This worked for me on python 2, and doesn't require PIL/pillow or any other dependencies (except cv2):
Edit: for python3 use base64.b64decode(encoded_data) to decode instead.
import cv2
import numpy as np
def data_uri_to_cv2_img(uri):
encoded_data = uri.split(',')[1]
nparr = np.fromstring(encoded_data.decode('base64'), np.uint8)
img = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
return img
data_uri = "data:image/jpeg;base64,/9j/4AAQ..."
img = data_uri_to_cv2_img(data_uri)
cv2.imshow(img)
You can just use both cv2 and pillow like this:
import base64
from PIL import Image
import cv2
from StringIO import StringIO
import numpy as np
def readb64(base64_string):
sbuf = StringIO()
sbuf.write(base64.b64decode(base64_string))
pimg = Image.open(sbuf)
return cv2.cvtColor(np.array(pimg), cv2.COLOR_RGB2BGR)
cvimg = readb64('R0lGODlhEAAQAMQAAORHHOVSKudfOulrSOp3WOyDZu6QdvCchPGolfO0o/XBs/fNwfjZ0frl3/zy7////wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAkAABAALAAAAAAQABAAAAVVICSOZGlCQAosJ6mu7fiyZeKqNKToQGDsM8hBADgUXoGAiqhSvp5QAnQKGIgUhwFUYLCVDFCrKUE1lBavAViFIDlTImbKC5Gm2hB0SlBCBMQiB0UjIQA7')
cv2.imshow(cvimg)
I found this simple solution.
import cv2
import numpy as np
import base64
image = "" # raw data with base64 encoding
decoded_data = base64.b64decode(image)
np_data = np.fromstring(decoded_data,np.uint8)
img = cv2.imdecode(np_data,cv2.IMREAD_UNCHANGED)
cv2.imshow("test", img)
cv2.waitKey(0)
Source : https://gist.github.com/HoweChen/7cdd09b08147133d8e1fbe9b52c24768

Categories