Corrupted image being saved by cv.SaveImage() in opencv - python

import sys, Image, scipy, cv2, numpy
from scipy.misc import imread
from cv2 import cv
from SRM import SRM
def ndarrayToIplImage (source):
"""Conversion of ndarray to iplimage"""
image = cv.CreateImageHeader((source.shape[1], source.shape[0]), cv.IPL_DEPTH_8U, 3)
cv.SetData(image, source.tostring(), source.dtype.itemsize * 3 * source.shape[1])
return image
"""Main Program"""
filename = "snap.jpeg"
Q = 64
im = imread(filename)
name = filename[:-4]
img = Image.fromarray(im)
if img.size[0] > 200 or img.size[1] > 200:
ratio = img.size[0]/img.size[1]
size = int(ratio*200), 200
img = numpy.array(img.resize(size, Image.ANTIALIAS))
srm = SRM(img, Q)
srm.initialization()
srm.segmentation()
classes, map = srm.map()
"""Converting ndarray to PIL Image to iplimage"""
pil_img = Image.fromarray(map)
cv_img = cv.CreateImageHeader(pil_img.size, cv.IPL_DEPTH_8U, 3)
cv.SetData(cv_img, pil_img.tostring(), pil_img.size[0]*3)
print type(cv_img) ##prints <type 'cv2.cv.iplimage'>
"""Using ndarrayToIplImage function also gives the same error!"""
"""
cv_img if of type iplimage but still gives error while using cv.ShowImage()
or cv.SaveImage().
There is no error displayed. Just the console hangs...
"""
I am using the SRM (Statistical Region Merging) Package available at this page.
I have just changed the example program given in the package. I had to convert the type returned by the SRM package functions to iplimage. There is no error in using the package but somewhere in using opencv functions.
This is the image that is saved after the console closes after hanging.
It used cv.SaveImage().
I tried cv2.imwrite() and I got this as the result:
This is the image that should have been saved. I used scipy.misc.imsave('image.jpg', map) to save this.

Why do you use IplImage and PIL? SRM library read numpy array and you get a numpy array from cv2.imread(image), then if you need to resize yuor image you can use opencv function cv2.resize(...). Finally you can save an image with opencv with cv2.imwrite(...) your code should appear like this:
import sys, cv2, numpy
from SRM import SRM
"""Main Program"""
filename = "snap.jpeg"
Q = 64
img = cv2.imread(filename)
name = filename[:-4]
if img.shape[0] > 200 or img.shape[1] > 200:
ratio = img.shape[0] * 1. / img.shape[1]
size = (int(ratio * 200), 200)
img = cv2.resize(img, size, interpolation=cv2.INTER_LANCZOS4)
srm = SRM(img, Q)
srm.initialization()
srm.segmentation()
classes, srmMap = srm.map() # Map is a python function, use different variable name
srmMap = srmMap.astype('uint8') # or you can try other opencv supported type
# I suppose that srmMap is your image returned as numpy array
cv2.imwrite('name.jpeg', srmMap)
# or
cv2.imshow('image', srmMap)
cv2.waitKey(0)

Related

How to embed hyperspectral image in Qlabel using PyQt5 in Python?

I have used Qpixmap for embedding a normal image in Qlabel in user interface and its working totally fine but when I'm trying to embed a hyperspectral image its showing error
Following is the code used -
`
library used - rasterio
img = rs.open('HYP.tif')
profile = img.profile
profile.update(count=3, compress='lzw')
full_img = img.read()
band1 = int(input('band number 1:'))
band2 = int(input('band number 2:'))
band3 = int(input('band number 3:'))
b1 = img.read(band1)
b2 = img.read(band2)
b3 = img.read(band3)
def normalize(array):
#Normalizes numpy arrays into scale 0.0 - 1.0
array_min, array_max = array.min(), array.max()
return (array - array_min) / (array_max - array_min)
# Normalize the bands
redn = normalize(b3)
greenn = normalize(b2)
bluen = normalize(b1)
rgb = np.dstack((bluen, redn, greenn))
rgb1 = rgb.T
rasterio.plot.show(rgb1)
rgb3 = rgb1 / rgb1.max()
rgb3 = rgb3 * 255
rgb3 = rgb3.astype(numpy.uint32)
rasterio.plot.show(rgb3)
file_list = [rgb1.read, greenn, bluen]
with rs.open('outimg.png', 'w', **profile) as dest:
for band_nr, src in enumerate(file_list, start=1):
dest.write(src, band_nr)
self.label_2.setPixmap(QtGui.QPixmap('outimg.png'))
`
When I'm displaying the image using show() function its working fine and same for saving the image but when I'm trying to embed it in Qlabel
(code -self.label_2.setPixmap(QtGui.QPixmap('outimg.png')))
its shwoing error -
foo: Sorry, can not handle images with 32-bit samples.
I want to know where is the mistake and how this can be done?

I'm having trouble with pasting a gif on an image using PIL

from PIL import Image, ImageSequence
import PIL
GIF_PATH = Image.open(r"C:\Users\me_\My\Filw\Path.gif")
IMAGE_PATH = Image.open(r"base.png")
frames = []
for frame in ImageSequence.Iterator(GIF_PATH):
output = IMAGE_PATH.copy()
frame_px = frame.load()
output_px = output.load()
transparent_foreground = frame.convert('RGBA')
transparent_foreground_px = transparent_foreground.load()
for x in range(frame.width):
for y in range(frame.height):
if frame_px[x, y] in (frame.info["background"], frame.info["transparency"]):
continue
output_px[x, y] = transparent_foreground_px[x, y]
output =output.resize([436,249], PIL.Image.NEAREST)
frames.append(output)
frames[0].save('output.gif',save_all = True, append_images = frames[1:], optimize = False, duration = 40, loop=0)
how would I paste the image to a specific location?
I'm pretty new so trying to get a grasp
I tried using imagechops offset but the image just wrapped around instead of moving

Converting NRRD file to JPG

i am trying to convert nrrd file into jpg by reading that nrrd image using pynrrd and then using the pixel i am trying to form an image but the out i am getting is terrible contrast image. Below is waht i have tried
import numpy as np
import nrrd
from PIL import Image
import numpy as np
filename = "/content/drive/MyDrive/CT.nrrd"
readdata, header = nrrd.read(filename)
print(readdata.shape) # (512, 512, 504)
for i in range(504):
if i == 200:
img = np.array(readdata[:,:,i])
print(img.shape)
print(np.amax(img))
img = (np.maximum(img, 0) / img.max()) * 255.0
img = Image.fromarray(np.uint8(img), mode = "L")
img.save(f'/content/testrgb{i}.png')
break
The output i am getting is this
Can someone please help me this
from PIL import Image
import numpy as np
import nrrd
def manipulating_nrrd_contrast(img, level):
img_c = img.astype(int).copy()
factor = (8 * (level+255)) / (255 * (259-level)) #This 8 here is the value that i changes manually by try and test and found out that this works best
img_c = factor * (img_c - 128) + 128
img_c = np.clip(img_c, 0, 255)
return img_c.astype(np.uint8)
filename = "/content/drive/MyDrive/CT.nrrd"
readdata, header = nrrd.read(filename)
tag_info = get_meta_data(header)
print(tag_info)
print(readdata.shape)
for i in range(readdata.shape[2]):
b = np.asarray(readdata[:,:,i]).astype(int)
final = Image.fromarray(manipulating_nrrd_contrast(b, 128))
final.save(f'/content/png/testrgb{i}.png')
And, The Result that i got is below

'str' object has no attribute 'copy' error when creating an image resizing function

I'm working on creating an image resizing function, and for some reason I'm receiving this error:
"'str' object has no attribute 'copy'"
The code I started with is
import os
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import image as mp_image
# Set a size for the figures
fig = plt.figure(figsize=(12, 12))
# Loop through subfolders
for root, folders, filenames in os.walk(src_folder):
image_num = 0
num_folders = len(folders)
for folder in sorted(folders):
# Increment the count of each image
image_num +=1
# Find the first image in the folder
file_name = os.listdir(os.path.join(root,folder))[0]
# Get the full path from the root folder
file_path = os.path.join(root,folder, file_name)
# Open the file using the matplotlib.image library
image = mp_image.imread(file_path)
# Add the image to the figure (which will have a row for each folder, each containing one column for the image)
a=fig.add_subplot(num_folders, 1, image_num)
# Add the image to the plot
image_plot = plt.imshow(image)
# Add a caption with the folder name
a.set_title(folder)
# Show the plot
plt.show()
which resulted with three images successfully.
The problem I'm facing is when I'm trying to create a resizing function, and the code I'm using is as follows:
def resize_image(src_image, size=(200,200), bg_color="white"):
from PIL import Image, ImageOps
# resize the image so the longest dimension matches our target size
src_image.thumbnail(size, Image.ANTIALIAS)
# Create a new square background image
new_image = Image.new("RGB", size, bg_color)
# Paste the resized image into the center of the square background
new_image.paste(src_image, (int((size[0] - src_image.size[0]) / 2), int((size[1] - src_image.size[1]) / 2)))
# return the resized image
return new_image
# Resizing image
target_size = (128,128)
pad_color = "black"
resized_img = resize_image(file_path.copy(), target_size, pad_color)
n_h, n_w = resized_img.size
print('New size:', n_h, 'x', n_w)
imgplot = plt.imshow(resized_img)
plt.show()
I'm unsure why I'm receiving the following error
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-13-ac35b6ef00b6> in <module>
17 target_size = (128,128)
18 pad_color = "black"
---> 19 resized_img = resize_image(file_path.copy(), target_size, pad_color)
20 n_h, n_w = resized_img.size
21 print('New size:', n_h, 'x', n_w)
AttributeError: 'str' object has no attribute 'copy'
Appreciate your help in advance!

Loading image pixel data gives unexpected result - Python - Pillow

Why does image.getdata() return different result second time I invoke it?
from PIL import Image
def write():
image = Image.open('image.jpg')
newimage = Image.new(image.mode, image.size)
pixels = [p for p in image.getdata()]
for i in range(100):
pixels[i] = (255,255,255)
newimage.putdata(pixels)
newimage.save('newimage.jpg')
print(list(newimage.getdata())[0:10])
def read():
image = Image.open('newimage.jpg')
pixels = [p for p in image.getdata()]
print(list(image.getdata())[0:10])
write()
read()
It gives me the following result:
Why is second set of data differ from the first one?

Categories

Resources