OpenCV gaussianblur making image loose colors - python

I am applying OpenCV's GaussianBlur on an image. Resulting image looks to lack the colors original image has.
My code:
originalImage = cv2.imread('path to original image',0)
blurredImage = cv2.GaussianBlur(originalImage,(15,15),0)
cv2.imwrite('path to save the new image', blurredImage)
Original image:
New image:
Is this correct behaviour?I want to retain the color details.

The problem is with the line reading the image as:
originalImage = cv2.imread('path to original image',0)
The param 0 in the cv2.imread() instructs the library to read grayscale image irrespective of the original image configuration. To fix this you can call cv2.imread() with no params as:
originalImage = cv2.imread('path to original image')
This command instructs the library to read the image in BGR config.
But if you want to read the image in the exact same format as it is, then you may need to call:
originalImage = cv2.imread('path to original image', -1)
You may refer to cv2.imread() docs for more info.

Related

Image.open() gives a plain white image

I am trying to edit this image:
However, when I run
im = Image.open(filename)
im.show()
it outputs a completely plain white image of the same size. Why is Image.open() not working? How can I fix this? Is there another library I can use to get non-255 pixel values (the correct pixel array)?
Thanks,
Vinny
Image.open actually seems to work fine, as does getpixel, putpixel and save, so you can still load, edit and save the image.
The problem seems to be that the temp file the image is saved in for show is just plain white, so the image viewer shows just a white image. Your original image is 16 bit grayscale, but the temp image is saved as an 8 bit grayscale.
My current theory is that there might actually be a bug in show where a 16 bit grayscale image is just "converted" to 8 bit grayscale by capping all pixel values to 255, resulting in an all-white temp image since all the pixels values in the original are above 30,000.
If you set a pixel to a value below 255 before calling show, that pixel shows correctly. Thus, assuming you want to enhance the contrast in the picture, you can open the picture, map the values to a range from 0 to 255 (e.g. using numpy), and then use show.
from PIL import Image
import numpy as np
arr = np.array(Image.open("Rt5Ov.png"))
arr = (arr - arr.min()) * 255 // (arr.max() - arr.min())
img = Image.fromarray(arr.astype("uint8"))
img.show()
But as said before, since save seems to work as it should, you could also keep the 16 bit grayscale depth and just save the edited image instead of using show.
you can use openCV library for loading images.
import cv2
img = cv2.imread('image file')
plt.show(img)

python simple substitute variableć„“ (opencv image processing)

enter image description here
Why img is same result with img_gray?
I think img must be showed original image.
You have to duplicate image
img_gray = img.copy()
Without copy() both variables gives access to the same image in memory.
It is standard behavior in Python.

how i can show image after image writing

I'm trying simple code that read an image and convert it to grey scale then show both of them, and finally save the grey scale image and display it after saving. The problem is that cv2.imshow (image show) for saved image doesn't work.
The images before image writing are displayed correctly and the image saved correctly in the same path but can't be displayed using cv2.imshow.
'''
python
'''
import cv2
img=cv2.imread('cover.jpg')
cv2.imshow('image', img)
img_grey = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
cv2.imshow('image_grey', img_grey)
savedimage='new.jpg'
cv2.imwrite('new.jpg',img_grey)
cv2.imshow('testsavedimage',savedimage)
cv2.waitKey(0)
I receive error for showing saved image
File "C:/1.py", line 8, in <module>
cv2.imshow('testsavedimage',savedimage)
TypeError: Expected Ptr<cv::UMat> for argument '%s
savedimage is just a string in this case. If you want to make sure that your grey scale image was saved properly, you need to first read it back into a Mat object:
cv2.imwrite('new.jpg',img_grey)
savedImg = cv2.imread('new.jpg')
cv2.imshow('testsavedimage', savedImg)
Hope this helps.
(PS #Mark Setchel is right, you should be using cv2.COLOR_BGR2GRAY here. This is because imread() and imshow() default to BGR colorspace, not RGB)

How to get title from an image in openCV python

I was wondering how to get a title from a image in OpenCV.
At the moment I have this:
#Load a color image in grayscale
img = cv2.imread('lena.jpg',0)
From here, I'd like to get the title from 'img' by doing something like
img.title()
but I don't find any method for doing this.
Any suggestion?
Thanks in advance.
You have set the name of the image, in which case you can store that and refer back to it in the future. There is no way of retriving it from the Mat object as all that stores is the data of the image itself.
instead of:
#Load a color image in grayscale
img = cv2.imread('lena.jpg',0)
save the file name first then use that wherever you need it
image_filename = 'lena.jpg'
img = cv2.imread(image_filename,0)
There is no direct method in opencv to extract the title from an image. After we load the image in opencv by "imread", the image will be transformed into arrays/matrices. Its all numericals(Christopher Nolan) stuff :P .
One way I can suggest is, you can find "contours" by applying some heuristics like averaging/mean/medium of Area, width, height etc. and also try applying "RLSA(Run Length Smoothing Algorithm)" on those classified contours.
Documention and Code for RLSA is here

Resize image in Python without losing EXIF data

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.

Categories

Resources