PIL.ImageOps.fit() gives AttributeError: 'str' object has no attribute 'size' - python-imaging-library

i`m getting an error while trying to crop my photo using PIL.ImageOps.fit()
*its
This is my code:
import sys
from PIL import ImageOps, Image, ImageChops
import PIL
#user comand-line input validation
if len(sys.argv) != 3:
sys.exit("Amount of argumets is not corrent")
name, newName = sys.argv[1], sys.argv[2]
splitedName, splitedNewName = name.split("."), newName.split(".")
formats =["jpg","jpeg","png"]
# print(splitedName[1],splitedNewName[1])
if splitedName[1] != splitedNewName[1] and splitedName not in formats:
sys.exit("Formats are not correct!")
#Photo processing
shirt = Image.open("shirt.png")
size = shirt.size
im2 = ImageOps.fit(name,size)
im2.paste(shirt,shirt)
im2.save(newName)
I`m getting an error which says that str doesn`t have attribute size:
Traceback (most recent call last):
File "/home/lev/CS50/shirt/shirt.py", line 26, in <module>
im2 = ImageOps.fit(name,size)
File "/home/lev/miniconda3/lib/python3.9/site-packages/PIL/ImageOps.py", line 461, in fit
bleed_pixels = (bleed * image.size[0], bleed * image.size[1])
AttributeError: 'str' object has no attribute 'size'

You are using ImageOps.fit() with as first argument the name of the image (variable name), which is a string. If you look up the documentation of ImageOps.fit(), you see that the first argument should be an image itself, not a filename.
Solution: change this line:
im2 = ImageOps.fit(name,size)
into:
im2 = ImageOps.fit(shirt,size)

Related

Convert pointcloud csv to hdf5 to train on PointCNN network

I am trying to train my point cloud data on PointCNN so I need to convert my dataset to hdf5 as used in PointCNN. PointCNN used the modelnet40_ply_hdf5_2048 dataset.
I have tried converting my custom dataset but I am having issues with the label.
I tried this to get the label/shape_names
shape_ids = {}
shape_ids = [line.rstrip() for line in open(os.path.join(PATH, 'filelist1.txt'))]
shape_names = ['_'.join(x.split('_')[0:-1]) for x in shape_ids]
datapath = [(shape_names[i], os.path.join(PATH, shape_names[i], shape_ids[i])) for i
in range(len(shape_ids))]
Convert to h5py file
import numpy as np
from tqdm import tqdm
import h5py
filenames = [line.rstrip() for line in open(os.path.join(PATH))]
f = h5py.File("filename", 'w')
data = np.zeros((len(filenames), 1024, 3))
for i in range(0, len(datapath)):
fn = datapath[i]
cls = classes[datapath[i][0]]
label = np.array([cls]).astype(np.int32)
csvreader = np.genfromtxt("data1/" + filenames[i] + ".csv", delimiter=",").astype(np.float32)
for j in range(0,1024):
data[i,j] = [csvreader[j][0], csvreader[j][1], csvreader[j][2]]
label
dset1 = f.create_dataset("data", data=data, compression="gzip", compression_opts=4)
dset2 = f.create_dataset("label", data=label, compression="gzip", compression_opts=1)
f.close()
It did convert successfully but when I tried to train on PointCNN
PointCNN training
------Building model-------
------Successfully Built model-------
Traceback (most recent call last):
File "train_pytorch.py", line 174, in <module>
current_data, current_label, _ = provider.shuffle_data(current_data, np.squeeze(current_label))
File "provider.py", line 28, in shuffle_data
idx = np.arange(len(labels))
TypeError: len() of unsized object

Getting 'OSError: -2' while converting a tif image into jpg image using python

I'm trying to convert tiff images into jpg format and use it later in opencv. It is working fine in my local system but when I am executing it over linux server which is not connected to internet it is getting failed while saving the Image object as jpg format.
I'm using python3.8 and had installed all the libraries and its dependencies using wheel files over server using pip.
Here is the piece of code:
import PIL
import cv2
def face_detect(sourceImagepath1, processedFileName, imagename, pdfname):
temp_path = TEMP_PATH
processed_path = PROCESSED_PATH
misc_path = MISC_PATH
# cascade file path1
cascpath1 = misc_path + 'frontalface_cascade.xml'
# Create harr cascade
faceCascade = cv2.CascadeClassifier(cascpath1)
# Read image with PIL
image_pil = Image.open(sourceImagepath1)
# Save image in jpg format
image_pil.save(temp_path + processedFileName + '.jpg')
# Read image with opencv
image_cv = cv2.imread(temp_path + processedFileName + '.jpg')
# Convert image into grayscale
image_gray = cv2.cvtColor(image_cv, cv2.COLOR_BGR2GRAY)
# Detect faces in the image
face = faceCascade.detectMultiScale(
image_gray,
scaleFactor=1.3,
minNeighbors=5,
minSize=(30, 30)
# flags = cv2.CASCADE_SCALE_IMAGE
)
if len(face) > 0:
# Coordinates based on auto-face detection
x, y, w, h = face[0][0], face[0][1], face[0][2], face[0][3]
crop_image = image_pil.crop([x - 20, y - 30, x + w + 40, y + h + 60])
crop_image.save(processed_path + imagename)
# Save tif file as pdf
image_pil.save(processed_path + pdfname, save_all=True)
# Close image object
image_pil.close()
return len(face)
Here TEMP_PATH,PROCESSED_PATH,MISC_PATH are global variables of syntax like '/Users/user/Documents/Temp/'. I'm getting error on line:
image_pil.save(temp_path + processedFileName + '.jpg')
Below is the error i'm getting when executing the file
Traceback (most recent call last):
File "*path_from_root_directory*/PYTHON_SCRIPTS/Script/staging.py", line 363, in <module>
auto_face_count = face_detect(sourceImagepath1, processedFileName, imagename, pdfname)
File "*path_from_root_directory*/PYTHON_SCRIPTS/Script/staging.py", line 71, in greyScaleCheck
image_pil.save(temp_path + processedFileName + '.jpg')
File "*path_from_root_directory*/python3.8/site-packages/PIL/Image.py", line 2201, in save
self._ensure_mutable()
File "*path_from_root_directory*/python3.8/site-packages/PIL/Image.py", line 624, in _ensure_mutable
self._copy()
File "*path_from_root_directory*/python3.8/site-packages/PIL/Image.py", line 617, in _copy
self.load()
File "*path_from_root_directory*/python3.8/site-packages/PIL/TiffImagePlugin.py", line 1122, in load
return self._load_libtiff()
File "*path_from_root_directory*/python3.8/site-packages/PIL/TiffImagePlugin.py", line 1226, in _load_libtiff
raise OSError(err)
OSError: -2
I have provided full privileges to python directory and its sub-directories/files. Anyone have any idea why I'm getting this error ?

How to find expected value of np.array using scipy.stats?

I am trying to get the expected value of a NumPy array but I am running into a problem when I pass my array into the function here is an example of what is happening:
a = np.ones(10)
stats.rv_continuous.expect(args=a)
I get this error:
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
stats.rv_continuous.expect(args=a)
TypeError: expect() missing 1 required positional argument: 'self'
If I try stats.rv_continuous.expect(a) , I get this error:
'numpy.ndarray' object has no attribute '_argcheck'
Can someone tell me how to get scipy.stats to work with an array?
update:
following bob's comment I changed the code to:
st=stats.rv_continuous()
ev = st.expect(args=signal_array)
print(ev)
where signal_array is a numpy array. However I now get this error:
Traceback (most recent call last):
File "C:\Users\...\OneDrive\Área de Trabalho\TickingClock\Main.py", line 35, in <module>
ev = st.expect(args=signal_array)
File "C:\Users\...\AppData\Local\Programs\Python\Python39\lib\site-packages\scipy\stats\_distn_infrastructure.py", line 2738, in expect
vals = integrate.quad(fun, lb, ub, **kwds)[0] / invfac
File "C:\Users\...\AppData\Local\Programs\Python\Python39\lib\site-packages\scipy\integrate\quadpack.py", line 351, in quad
retval = _quad(func, a, b, args, full_output, epsabs, epsrel, limit,
File "C:\Users\...\AppData\Local\Programs\Python\Python39\lib\site-packages\scipy\integrate\quadpack.py", line 465, in _quad
return _quadpack._qagie(func,bound,infbounds,args,full_output,epsabs,epsrel,limit)
File "C:\Users\...\AppData\Local\Programs\Python\Python39\lib\site-packages\scipy\stats\_distn_infrastructure.py", line 2722, in fun
return x * self.pdf(x, *args, **lockwds)
File "C:\Users\...\AppData\Local\Programs\Python\Python39\lib\site-packages\scipy\stats\_distn_infrastructure.py", line 1866, in pdf
args, loc, scale = self._parse_args(*args, **kwds)
TypeError: _parse_args() got multiple values for argument 'loc'

python AttributeError when attempting to save excel chart using PIL

I am trying to save an chart from excel into a file, which I want to use later in a powerpoint presentation, but the code I am running keeps on coming up with
"AttributeError: 'NoneType' object has no attribute 'save'" .
Have been looking around google/stackoverflow but none of the suggestions I can find actually help, I keep on getting the error.
The code I am trying is below,
import win32com.client
import PIL
folder_path = r'C:/temp/Monthly_Graphs.xlsm'
xlApp = win32com.client.DispatchEx('Excel.Application')
wb = xlApp.Workbooks.Open(folder_path)
xlApp = win32com.client.DispatchEx('Excel.Application')
wb = xlApp.Workbooks.Open(folder_path)
wb.Sheets('Sheet1').Shapes('Sheet1_Pie_Chart').CopyPicture()
pie_image = PIL.ImageGrab.grabclipboard()
pie_image.savefig(r'C:/temp/pie_test.bmp','BMP')
the traceback is below
Traceback (most recent call last):
File "<ipython-input-12-b8e52c17e4d1>", line 1, in <module>
runfile('C:/python/stackoverflow_1.py', wdir='C:/python')
File "C:\Users\xxxxxxx\AppData\Local\conda\conda\envs\py64bit\lib\site-packages\spyder\utils\site\sitecustomize.py", line 710, in runfile
execfile(filename, namespace)
File "C:\Users\xxxxxxx\AppData\Local\conda\conda\envs\py64bit\lib\site-packages\spyder\utils\site\sitecustomize.py", line 101, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)
File "C:/python/stackoverflow_1.py", line 26, in <module>
pie_image.savefig(r'C:/temp/pie_test.bmp','BMP')
AttributeError: 'NoneType' object has no attribute 'savefig'
Managed to get it to work by referring to the below Q and setting the format of the CopyPicture line. Issue seems to be that excel default copy of the image is not in a format that PIL understands
Python Export Excel Sheet Range as Image
import win32com.client
from PIL import ImageGrab
import win32clipboard as clip
folder_path = r'C:/temp/Monthly_Graphs.xlsm'
xlApp = win32com.client.DispatchEx('Excel.Application')
wb = xlApp.Workbooks.Open(folder_path)
xlApp = win32com.client.DispatchEx('Excel.Application')
wb = xlApp.Workbooks.Open(folder_path)
wb.Sheets('Sheet1').Shapes('Sheet1_Pie_Chart').CopyPicture(Format=clip.CF_BITMAP)
pie_image = ImageGrab.grabclipboard()
pie_image.save(r'C:/temp/pie_test.bmp','BMP')

Loading a pretrained model fails when multiple GPU was used for training

I have trained a network model and saved its weights and architecture via checkpoint = ModelCheckpoint(filepath='weights.hdf5') callback. During training, I am using multiple GPUs by calling the funtion below:
def make_parallel(model, gpu_count):
def get_slice(data, idx, parts):
shape = tf.shape(data)
size = tf.concat([ shape[:1] // parts, shape[1:] ],axis=0)
stride = tf.concat([ shape[:1] // parts, shape[1:]*0 ],axis=0)
start = stride * idx
return tf.slice(data, start, size)
outputs_all = []
for i in range(len(model.outputs)):
outputs_all.append([])
#Place a copy of the model on each GPU, each getting a slice of the batch
for i in range(gpu_count):
with tf.device('/gpu:%d' % i):
with tf.name_scope('tower_%d' % i) as scope:
inputs = []
#Slice each input into a piece for processing on this GPU
for x in model.inputs:
input_shape = tuple(x.get_shape().as_list())[1:]
slice_n = Lambda(get_slice, output_shape=input_shape, arguments={'idx':i,'parts':gpu_count})(x)
inputs.append(slice_n)
outputs = model(inputs)
if not isinstance(outputs, list):
outputs = [outputs]
#Save all the outputs for merging back together later
for l in range(len(outputs)):
outputs_all[l].append(outputs[l])
# merge outputs on CPU
with tf.device('/cpu:0'):
merged = []
for outputs in outputs_all:
merged.append(merge(outputs, mode='concat', concat_axis=0))
return Model(input=model.inputs, output=merged)
With the testing code:
from keras.models import Model, load_model
import numpy as np
import tensorflow as tf
model = load_model('cpm_log/deneme.hdf5')
x_test = np.random.randint(0, 255, (1, 368, 368, 3))
output = model.predict(x = x_test, batch_size=1)
print output[4].shape
I got the error below:
Traceback (most recent call last):
File "cpm_test.py", line 5, in <module>
model = load_model('cpm_log/Jun5_1000/deneme.hdf5')
File "/usr/local/lib/python2.7/dist-packages/keras/models.py", line 240, in load_model
model = model_from_config(model_config, custom_objects=custom_objects)
File "/usr/local/lib/python2.7/dist-packages/keras/models.py", line 301, in model_from_config
return layer_module.deserialize(config, custom_objects=custom_objects)
File "/usr/local/lib/python2.7/dist-packages/keras/layers/__init__.py", line 46, in deserialize
printable_module_name='layer')
File "/usr/local/lib/python2.7/dist-packages/keras/utils/generic_utils.py", line 140, in deserialize_keras_object
list(custom_objects.items())))
File "/usr/local/lib/python2.7/dist-packages/keras/engine/topology.py", line 2378, in from_config
process_layer(layer_data)
File "/usr/local/lib/python2.7/dist-packages/keras/engine/topology.py", line 2373, in process_layer
layer(input_tensors[0], **kwargs)
File "/usr/local/lib/python2.7/dist-packages/keras/engine/topology.py", line 578, in __call__
output = self.call(inputs, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/keras/layers/core.py", line 659, in call
return self.function(inputs, **arguments)
File "/home/muhammed/DEV_LIBS/developments/mocap/pose_estimation/training/cpm/multi_gpu.py", line 12, in get_slice
def get_slice(data, idx, parts):
NameError: global name 'tf' is not defined
By inspecting the error output, I decide that the problem is with the parallelization code. However, I can't resolve the issue.
You may need to use custom_objects to enable loading of the model.
import tensorflow as tf
model = load_model('model.h5', custom_objects={'tf': tf,})