CSV Class reader not getting actual image - python

I have a CSV file reader which reads a csv file with one column and obtains data about the image such as its label. After much debugging I have found my all data about the image is read but I'm missing the actual get image part, so currently, cv2 shows the input as a black box.
Im not sure what to do to achieve this, and need some assistance
My CSV Reader Below
def __init__(self, csvPath, imageHeight, imageWidth, transform = None):
"""
Arguments:
A CSV File Path
Path to Image Foldr
Extension of Images
PIL Transforms
"""
self.dataFromCSV = pD.read_csv(csvPath)
self.dataLabels = nP.asarray(self.dataFromCSV.iloc[:, 0])
self.imageHeight = imageHeight
self.imageWidth = imageWidth
self.transform = transform
def __getitem__(self, index):
singleImageLabel = self.dataLabels[index]
imagePath = singleImageLabel.split(";")[0]
print ('Path: ' + str(imagePath))
originalImage = cv2.imread(imagePath)
cv2.imshow('IMAGE', originalImage)
# Create an Empty Numpy Array to Fill
imageAsNumpy = nP.ones((32, 32), dtype = 'uint8')
# Fill the Numpy Array with Data from Pandas DF
for i in range(1):
rowPosition = (i-1) // self.imageHeight
columnPosition = (i-1) % self.imageWidth
indexFirst = self.dataFromCSV.iloc[index][i].split(";")[3]
indexLast = self.dataFromCSV.iloc[index][i].split(";")[6]
imageAsNumpy[rowPosition][columnPosition] = indexFirst + indexLast
print ('LABEL: ' + str(singleImageLabel))
cv2.imshow('INPUT',imageAsNumpy)
cv2.waitKey(0)
cv2.destroyAllWindows()
# Convert Image from Numpy Array to PIL Image, Mode 'L' is for Grayscale
imageAsImage = Image.fromarray(imageAsNumpy)
imageAsImage = imageAsImage.convert('1')
# Transform Image to Tensor
if self.transform is not None:
imageAsTensor = self.transform(imageAsImage)
# Transform Label to Tensor
labelAsLabel = int(singleImageLabel.split(";")[7])
labelAsTensor = torch.from_numpy(nP.array(labelAsLabel))
# print ('Target: ' + str(labelAsTensor))
# Return Image & the Label
return (imageAsTensor, labelAsLabel)
def __len__(self):
return len(self.dataFromCSV.index)

Related

raise KeyError(key) from err KeyError: 'pixels' in my project

raise KeyError(key) from err
KeyError: 'pixels'
Hi,I am a beginner and wanted to convert row to an image and this error appeared to me,what does it mean?and what is the solution?
# import these libraries
import numpy as np
import pandas as pd
import cv2
import utils
import os
# data
data = pd.read_csv('test.csv') # Path of the .csv file
#print(data.shape) # to check the shape
#print(data.head(5)) # Use this to print the first 5 lines of the data, to understand it better
def convert2image(row):
pixels = row['pixels'] # in out dataset, the row heading was 'pixels'
img = np.array(pixels.split())
img = img.reshape(48,48) # dimensions of the image
image = np.zeros((48,48,3)) # empty matrix
image[:,:,0] = img
image[:,:,1] = img
image[:,:,2] = img
return image.astype(np.uint8) # return the image
count = 0
for i in range(1, 6): #data.shape[0]):
face = data.iloc[i] # remove one row from the data
img = convert2image(face) # send this row of data to the function convert2image
count = count + 1 # counter to save the images with different name
cv2.imwrite(r'C:/Users/sanch/Desktop/Data/Python_projects/Emotion_reco/test/'+ str(count) +'.jpg',img) # path where you want to save the image

Display Dicom image using PIL(PILLOW) Python Library

I am trying to read and display DICOM(.dcm) images using below code:-
import pydicom as dicom
import numpy as np
from PIL import Image, ImageEnhance, ImageOps
from PIL.ImageQt import ImageQt
def display_dicom_images(self, folder_Path):
try:
# Image parameters
image_width = 382
image_height = 382
image_depth = 3
self.total_images_in_folder = len(glob.glob1(folder_Path,"*"))
# Select the center image for display
self.current_image_number = round(self.total_images_in_folder / 2)
self.display_number = self.current_image_number
image_dtype = np.uint8
pixel_array = np.ndarray([self.total_images_in_folder, image_height, image_width, image_depth]).astype(image_dtype)
# load images here, once better MR images are acquired
for image_index in range(0, self.total_images_in_folder):
# for DICOM
image_path = folder_Path + "/" + str(image_index) + ".dcm"
scan_image = dicom.dcmread(image_path)
scan_image = scan_image.pixel_array.astype(image_dtype)
pixel_array[image_index, :scan_image.shape[0], :scan_image.shape[1], :scan_image.shape[2]] = scan_image
return pixel_array
But getting error:-
IndexError('tuple index out of range',)
i am using pillow python library for image.
How do you know scan_image.shape is of length 3? MR images should only be monochrome, which would make image_depth = 1 and the length of scan_image.shape equal to 2.
C.8.3.1.1.3 Photometric Interpretation
Enumerated Values:
MONOCHROME1
MONOCHROME2

Python dict to csv

I have written a script to find image size and aspect ratio of all images in a directory along with their corresponding filepaths, I want to print dict values to csv file with following headers width,height,aspect-ratio and filepath
import os
import json
from PIL import Image
folder_images = "/home/user/Desktop/images"
size_images = dict()
def yocd(a,b):
if(b==0):
return a
else:
return yocd(b,a%b)
for dirpath, _, filenames in os.walk(folder_images):
for path_image in filenames:
if path_image.endswith(".png") or path_image.endswith('.jpg') or path_image.endswith('.JPG') or path_image.endswith('.jpeg'):
image = os.path.abspath(os.path.join(dirpath, path_image))
""" ImageFile.LOAD_TRUNCATED_IMAGES = True """
try:
with Image.open(image) as img:
img.LOAD_TRUNCATED_IMAGES = True
img.verify()
print('Valid image')
except Exception:
print('Invalid image')
img = False
if img is not False:
width, heigth = img.size
divisor = yocd(width, heigth)
w = str(int(width / divisor))
h = str(int(heigth / divisor))
aspectratio = w+':'+h
size_images[image] = {'width': width, 'heigth': heigth,'aspect-ratio':aspectratio,'filepath': image}
for k, v in size_images.items():
print(k, '-->', v)
with open('/home/user/Documents/imagesize.txt', 'w') as file:
file.write(json.dumps(size_images))```
You can add a (properly constructed) dict directly to a pandas.DataFrame. Then, DataFrames have a .to_csv() function.
Here are the docs:
Pandas: Create a DataFrame
Pandas: Write to CSV
Without dependencies (but you may have to tweak the formatting)
csv_sep = ';' # choose here wich field separatar you want
with open('your_csv', 'w') as f:
# header
f.write("width"+csv_sep"+height"+csv_sep"+aspect-ratio"+csv_sep+"filepath\n")
# data
for img in size_images:
fields = [img['width'], img['height'], img['aspect-ratio'], img['filepath']]
f.write(csv_sep.join(fields)+'\n')

OpenCV Panorama: TypeError: cannot unpack non-iterable NoneType object

I'm trying to make a panorama from a image set. I'm using Spyder, OpenCV 3.4 and Python 3.7. Here's the code:
The main:
from stitches import Stitcher
#from PIL import Image
import os
import glob
import numpy as np
import imutils
import cv2
cap = cv2.VideoCapture('C:/Users/VID_20181208_111037881.mp4')
img_dir = "C:/Users/user/images"
data_path = os.path.join(img_dir, '*g')
files = glob.glob(data_path)
args = []
for f1 in files:
img = cv2.imread(f1)
args.append(img)
def retImg(img):
return img
for i in args:
j = i+1
frame = retImg(i)
frame2 = retImg(j)
#imageA = cv2.imread(frame)
#imageB = cv2.imread(frame2)
imageA = imutils.resize(frame, width=400)
imageB = imutils.resize(frame2, width=400)
# stitch the images together to create a panorama
stitcher = Stitcher()
(result, vis) = stitcher.stitch([imageA, imageB], showMatches=False)
frame = result
# show the images
cv2.imshow("Keypoint Matches", vis)
cv2.imshow("Result", result)
cv2.waitKey(0)
The stitch inside stitches.py:
def stitch(self, images, ratio=0.75, reprojThresh=4.0, showMatches=False):
# unpack the images, then detect keypoints and extract
# local invariant descriptors from them
(imageB, imageA) = images
(kpsA, featuresA) = self.detectAndDescribe(imageA)
(kpsB, featuresB) = self.detectAndDescribe(imageB)
# match features between the two images
M = self.matchKeypoints(kpsA, kpsB, featuresA, featuresB, ratio, reprojThresh)
# if the match is None, then there aren't enough matched
# keypoints to create a panorama
if M is None:
return None
# together
(matches, H, status) = M
result = cv2.warpPerspective(imageA, H, (imageA.shape[1] + imageB.shape[1], imageA.shape[0]))
result[0:imageB.shape[0], 0:imageB.shape[1]] = imageB
# check to see if the keypoint matches should be visualized
if showMatches:
vis = self.drawMatches(imageA, imageB, kpsA, kpsB, matches, status)
# return a tuple of the stitched image and the
# visualization
return (result, vis)
# return the stitched image
return result
When I compile it, the following error is shown:
File "C:/Users/user/panorama.py", line 44, in <module>
(result, vis) = stitcher.stitch([imageA, imageB], showMatches=False)
TypeError: cannot unpack non-iterable NoneType object
And I cannot understand why. I'm new to Python, so maybe this mistake is really simple, but I don't know what to do here. Thanks by advance!

How to save a movie made from pictures by OpenCV in Python

I wrote a Python program with OpenCV that:
scans the folder with images
does some operations on them with respect to their order
returns a list IMGs of processed images
Now what I want to do, is to save the list IMGs of new pictures as a e.g. .avi movie. How to do such operation? I intentionally want to save pictures from a list after whole process of filtration etc.
import os
import cv2
import numpy as np
folder_name = 'trial1'
extension = '.bmp'
path = os.getcwd()
GB_kernel = (13,13)
""" List all .bmp images names from a folder """
def folder_content(folder_name, extension):
dir_content = os.listdir(folder_name)
folder_content_ext = []
for file in dir_content:
if file.endswith(extension):
folder_content_ext.append(file)
return folder_content_ext
IMG_names = folder_content(folder_name, extension)
""" Some OpenCV operations on images """
""" Loop over all images. Iterator i is important in the future """
IMGs = []
for i in range(len(IMG_names)):
""" Define path to basic image """
img = path + '\\' + folder_name + '\\' + IMG_names[i]
""" read this image """
image = cv2.imread(img, cv2.IMREAD_GRAYSCALE)
""" some operation - gaussian blur """
pre_filt = cv2.GaussianBlur(image, GB_kernel, 0)
""" contain blurred img in a list """
IMGs.append(pre_filt)
cv2.imshow('Gaussian Blur', pre_filt)
WKey = 1
if cv2.waitKey(WKey) & 0xFF == ord('q'):
break
cv2.destroyAllWindows()
""" HOW?? """
save_list_of_matrix_as_movie(IMGs)
Thanks for any help and hints.
You can try the code below.
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Create video from images in a list.
Idea from:
http://tsaith.github.io/combine-images-into-a-video-with-python-3-and-opencv-3.html
"""
import os
import time
import cv2
folder_name = 'trial1'
extension = '.bmp'
video_file = 'out.avi'
path = os.getcwd()
GB_kernel = (13, 13)
# %%
def folder_content():
"""
List all images names with given extension from a folder.
"""
dir_content = os.listdir(folder_name)
folder_content_ext = []
for file in dir_content:
if file.endswith(extension):
folder_content_ext.append(file)
return folder_content_ext
# %%
def img_2_matrix(img_names):
"""
Some OpenCV operations on images
Loop over all images. Iterator i is important in the future
"""
imgs = []
for i in range(len(img_names)):
# Define path to basic image
img = os.path.join(path, folder_name, img_names[i])
# read this image
image = cv2.imread(img, cv2.IMREAD_GRAYSCALE)
# some operation - gaussian blur
pre_filt = cv2.GaussianBlur(image, GB_kernel, 0)
# contain blurred img in a list
imgs.append(pre_filt)
cv2.imshow('Gaussian Blur', pre_filt)
wkey = 1
if cv2.waitKey(wkey) & 0xFF == ord('q'):
break
return imgs
# %%
def save_list_of_matrix_as_movie(imgs):
"""
"""
shape = (imgs[0].shape[1], imgs[0].shape[0])
fourcc = cv2.VideoWriter_fourcc(*"XVID") # XVID for avi, mp4v for mp4
out = cv2.VideoWriter(video_file, fourcc, 20.0, shape, 0)
print("\nHit 'q' to exit")
for frame in imgs:
pre_filt = cv2.GaussianBlur(frame, GB_kernel, 0)
out.write(pre_filt) # Write out frame to video
cv2.imshow("video", pre_filt)
if(cv2.waitKey(1) & 0xFF) == ord("q"): # Hit `q` to exit
break
return out
# %%
def release(out):
"""
Release everything if job is finished
"""
cv2.destroyAllWindows()
out.release()
# %%
if __name__ == "__main__":
# %%
TIC = time.time()
# %%
img_names = folder_content()
imgs = img_2_matrix(img_names)
out = save_list_of_matrix_as_movie(imgs)
release(out)
# %%
print("Time elapsed: %0.2f s" % (time.time() - TIC))

Categories