I need convert/load jpg2000 images (24 BIT RGBI True Color) to png/jpg for further usage and struggled quite a bit to get them loaded at all on windows. Succeeded with a pgmagic installation on windows, but the RGBI images come out as grayscale.
Output image generated with:
from pgmagick import Image
img = Image("path")
img.write('output.jpg')
What am I missing here?
Found the answer myself:
I had to use osgeo:
from osgeo import gdal
from PIL import Image
dataset = gdal.open("path", gdal.GA_ReadOnly)
img = dataset.ReadAsArray()
img_trnsp = img.transpose()
final_image = Image.fromarray(img_trnsp)
Related
I wrote the following code to resize images in a folder to 100*100 and save the images in the same folder using for loop.I am wondering why it isn't working.
The following is the code I have written:
import cv2
import glob
images=glob.glob("*.jpg")
for image in images:
img=cv2.imread(image,0)
re=cv2.resize(img,(100,100))
cv2.imshow("Hey",re)
cv2.waitKey(500)
cv2.destroyAllWindows()
cv2.imwrite("resized_"+image,re)
I executed this:
nsu#NSU:~/Desktop/cryptology$ python3 img2.py
I got no error:
nsu#NSU:~/Desktop/cryptology$ python3 img2.py
nsu#NSU:~/Desktop/cryptology$
But the folder where i have saved the images and code is as it is...
what should i do?
**A viewer posted an answer which resulted the same.
**The problem MAY not be with the code.
**Please consider this
If you like you can use very robust module of python called Pillow for image manipulation, so first do pip3 install pillow
then run this code
from PIL import Image
import glob
images=glob.glob("*.jpg")
for im in images:
# print(im)
img = Image.open(im)
img = img.resize((100, 100), Image.ANTIALIAS)
img.save(im+'_resized.jpg')
hope it helps ... you need to improve the code if you want to keep the aspect ratio of the image
I am trying to convert 8 bit images to 10 bit. I thought it would be as easy as changing the bin values. I've tried to pillow and cv-python:
from PIL import Image
from numpy import asarray
import cv2
path = 'path/to/image'
img = Image.open(path)
data = asarray(img)
newdata = (data/255)*1023 #2^10 is 1024
img2 = Image.fromarray(newdata) #this fails
cv2.imwrite('path/newimage.png, newdata)
While cv2.imwrite successfully writes the new file, it is still encoded as an 8bit image even though bin goes up to 1023.
$ file newimage.png
newimage.png: PNG Image data, 640 x 480, 8-bit/color RGB, non-interlaced
Is there another way in either python or linux that can convert 8-bit to 10-bit?
Lots of things going wrong here.
You are mixing OpenCV (cv2.imwrite) with PIL (Image.open) for no good reason. Don't do that, you will confuse yourself as they use different RGB/BGR orderings and conventions,
You are trying to store 10-bit numbers in 8-bit vectors,
You are trying to hold 3 16-bit RGB pixels in a PIL Image which will not work as RGB images must be 8-bit in PIL.
I would suggest:
import cv2
import numpy as np
# Load image
im = cv2.imread(IMAGE, cv2.IMREAD_COLOR)
res = im.astype(np.uint16) * 4
cv2.imwrite('result.png', res)
I found a solution using pgmagick wrapper for python
import pgmagick as pgm
imagePath = 'path/to/image.png'
saveDir = '/path/to/save'
img = pgm.Image(imagePath)
img.depth(10) #sets to 10 bit
save_path = os.path.join(saveDir,'.'.join([filename,'dpx']))
img.write(save_path)
I am currently learning Image detection using CNN etc. I found out a good article here which explain the face detection steps using OpenCV. I followed each and every steps. But I am really stuck since hours when trying to test a single sample image. Below is the code I used in google Colab:
import cv2
import matplotlib.pyplot as plt
import dlib
import os
from imutils import face_utils
font = cv2.FONT_HERSHEY_SIMPLEX
cascPath=r'C:\Users\randomUser\Desktop\haarcascade_frontalface_default.xml'
eyePath = r'C:\Users\randomUser\Desktop\haarcascade_eye.xml'
smilePath = r'C:\Users\randomUser\Desktop\haarcascade_smile.xml'
faceCascade = cv2.CascadeClassifier(cascPath)
eyeCascade = cv2.CascadeClassifier(eyePath)
smileCascade = cv2.CascadeClassifier(smilePath)
# even if I use the below path, I am still getting the error.
path = r'C:\Users\randomUser\Desktop\imagedata.jpeg'
gray = cv2.imread('imagedata.jpeg')
plt.figure(figsize=(12,8))
plt.imshow(gray, cmap='gray')
plt.show()
I have downloaded all the default files as mentioned above in my directory location along with the test image imagedata
However, when I am running the first few steps, I am getting the below error :(
I have tried giving physical path but I don't understand what am I missing.
I ran through different articles that explain the nature of the error, but none of them helped so I thought of asking here directly.
You should:
print( gray.shape )
after you read it. Because most likely you're reading a non-existent file that renders all code below that moot.
The issue that I was facing was because of the google drive path. After researching and using the Image path, I found out that when using colab, and mounting the google drive, even if you give the absolute path, it will add /content at the beginning of the path. Just because of this the path was not correct.
I think I found the error:
# This is what you have
path = r'C:\Users\randomUser\Desktop\imagedata.jpeg'
gray = cv2.imread('imagedata.jpeg')
# This is what you should have
path = r'C:\Users\randomUser\Desktop\imagedata.jpeg'
gray = cv2.imread(path) # <-- you weren't using the path of the image
Opening the image with PIL?
from PIL import Image
path = r'C:\Users\randomUser\Desktop\imagedata.jpeg'
gray = Image.open(path).convert("L") # L to open the image in gray scale
I want to read the alpha channel from a tiff image using Python OpenCV. I am using Enthought Canopy with OpenCV 2.4.5-3 module.
I followed the OpenCV website's tutorial using cv2.imread, but it doesn't seem to work.
What I have now is:
import cv2
image = cv2.imread('image.tif', -1)
Then I used: print (image.shape), it still shows the (8192, 8192, 3). But I used Matlab to read the same image, I can see the dimension of this image is (8192, 8192, 4).
I am not sure what should I do to read the alpha channel of this image.
Thanks in advance!!
Nan
This is an old question, but just in case someone else stumbles on it: if img.tiff is a 4-channel TIFF, then
import cv2
img = cv2.imread('img.tiff', cv2.IMREAD_UNCHANGED)
print img.shape
yields (212,296,4) as expected.
If you then use
channels = cv2.split(img)
you can reference the alpha layer (channels[3]) - for instance, as a mask.
The idea for this was taken from How do I use Gimp / OpenCV Color to separate images into coloured RGB layers? which cleverly uses a fake layer and merge to enable recovery of the individual RGB layers in their actual colours.
I found a solution this problem in converting the original image to RBGA format through PIL library.
from PIL import Image
import numpy as np
import cv2
path_to_image = 'myimg.png'
image = Image.open(path_to_image).convert('RGBA')
image.save(path_to_image)
image = cv2.imread(path_to_image, cv2.IMREAD_UNCHANGED)
print image.shape
out > (800, 689, 4)
I solved the same problem with:
pip install --upgrade opencv-python
I need to resize jpg images with Python without losing the original image's EXIF data (metadata about date taken, camera model etc.). All google searches about python and images point to the PIL library which I'm currently using, but doesn't seem to be able to retain the metadata. The code I have so far (using PIL) is this:
img = Image.open('foo.jpg')
width,height = 800,600
if img.size[0] < img.size[1]:
width,height = height,width
resized_img = img.resize((width, height), Image.ANTIALIAS) # best down-sizing filter
resized_img.save('foo-resized.jpg')
Any ideas? Or other libraries that I could be using?
There is actually a really simple way of copying EXIF data from a picture to another with only PIL. Though it doesn't permit to modify the exif tags.
image = Image.open('test.jpg')
exif = image.info['exif']
# Your picture process here
image = image.rotate(90)
image.save('test_rotated.jpg', 'JPEG', exif=exif)
As you can see, the save function can take the exif argument which permits to copy the raw exif data in the new image when saving. You don't actually need any other lib if that's all you want to do. I can't seem to find any documentation on the save options and I don't even know if that's specific to Pillow or working with PIL too. (If someone has some kind of link, I would enjoy if they posted it in the comments)
import jpeg
jpeg.setExif(jpeg.getExif('foo.jpg'), 'foo-resized.jpg')
http://www.emilas.com/jpeg/
You can use pyexiv2 to copy EXIF data from source image. In the following example image is resized using PIL library, EXIF data copied with pyexiv2 and image size EXIF fields are set with new size.
def resize_image(source_path, dest_path, size):
# resize image
image = Image.open(source_path)
image.thumbnail(size, Image.ANTIALIAS)
image.save(dest_path, "JPEG")
# copy EXIF data
source_image = pyexiv2.Image(source_path)
source_image.readMetadata()
dest_image = pyexiv2.Image(dest_path)
dest_image.readMetadata()
source_image.copyMetadataTo(dest_image)
# set EXIF image size info to resized size
dest_image["Exif.Photo.PixelXDimension"] = image.size[0]
dest_image["Exif.Photo.PixelYDimension"] = image.size[1]
dest_image.writeMetadata()
# resizing local file
resize_image("41965749.jpg", "resized.jpg", (600,400))
Why not using ImageMagick?
It is quite a standard tool (for instance, it is the standard tool used by Gallery 2); I have never used it, however it has a python interface as well (or, you can also simply spawn the command) and most of all, should maintain EXIF information between all transformation.
Here's an updated answer as of 2018. piexif is a pure python library that for me installed easily via pip (pip install piexif) and worked beautifully (thank you, maintainers!). https://pypi.org/project/piexif/
The usage is very simple, a single line will replicate the accepted answer and copy all EXIF tags from the original image to the resized image:
import piexif
piexif.transplant("foo.jpg", "foo-resized.jpg")
I haven't tried yet, but it looks like you could also perform modifcations easily by using the load, dump, and insert functions as described in the linked documentation.
For pyexiv2 v0.3.2, the API documentation refers to the copy method to carry over EXIF data from one image to another. In this case it would be the EXIF data of the original image over to the resized image.
Going off #Maksym Kozlenko, the updated code for copying EXIF data is:
source_image = pyexiv2.ImageMetadata(source_path)
source_image.read()
dest_image = pyexiv2.ImageMetadata(dest_path)
dest_image.read()
source_image.copy(dest_image,exif=True)
dest_image.write()
You can use pyexiv2 to modify the file after saving it.
from PIL import Image
img_path = "/tmp/img.jpg"
img = Image.open(img_path)
exif = img.info['exif']
img.save("output_"+img_path, exif=exif)
Tested in Pillow 2.5.3
It seems #Depado's solution does not work for me, in my scenario the image does not even contain an exif segment.
pyexiv2 is hard to install on my Mac, instead I use the module pexif https://github.com/bennoleslie/pexif/blob/master/pexif.py. To "add exif segment" to an image does not contain exif info, I added the exif info contained in an image which owns a exif segment
from pexif import JpegFile
#get exif segment from an image
jpeg = JpegFile.fromFile(path_with_exif)
jpeg_exif = jpeg.get_exif()
#import the exif segment above to the image file which does not contain exif segment
jpeg = JpegFile.fromFile(path_without_exif)
exif = jpeg.import_exif(jpeg_exif)
jpeg.writeFile(path_without_exif)
Updated version of Maksym Kozlenko
Python3 and py3exiv2 v0.7
# Resize image and update Exif data
from PIL import Image
import pyexiv2
def resize_image(source_path, dest_path, size):
# resize image
image = Image.open(source_path)
# Using thumbnail, then 'size' is MAX width or weight
# so will retain aspect ratio
image.thumbnail(size, Image.ANTIALIAS)
image.save(dest_path, "JPEG")
# copy EXIF data
source_exif = pyexiv2.ImageMetadata(source_path)
source_exif.read()
dest_exif = pyexiv2.ImageMetadata(dest_path)
dest_exif.read()
source_exif.copy(dest_exif,exif=True)
# set EXIF image size info to resized size
dest_exif["Exif.Photo.PixelXDimension"] = image.size[0]
dest_exif["Exif.Photo.PixelYDimension"] = image.size[1]
dest_exif.write()
PIL handles EXIF data, doesn't it? Look in PIL.ExifTags.