I am shown with the given below problem: let me help how to solve.Thanks.
#Traceback (most recent call last):
#File "C:/Users/Admin/PycharmProjects/frec/part3.py", line 15, in
#<module>
#Training_Data.append(np.asarray(images, dtype=np.uint8))
#File "C:\Users\Admin\.virtualenvs\frec\lib\site-
#packages\numpy\core\numeric.py", line 538, in asarray
#return array(a, dtype, copy=False, order=order)
#TypeError: int() argument must be a string, a bytes-like object or a
#number,
#not 'NoneType'
nothing i have no idea how to find solution for it.
for i, files in enumerate(onlyfiles):
image_path = data_path + onlyfiles[i]
images = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)
Training_Data.append(np.asarray(images, dtype=np.uint8))
Labels.append(i)
no idea.
Probably, the index's in the for loop.
2 issues.
1) no indentation of the body of the for loop. The code as you have shown does not loop over the last 4 lines. You need to indent these if you want them to be evaluated in the context of the loop. Otherwise, your indexes, i and files are not defined.
for i, files in enumerate(onlyfiles):
image_path = data_path + onlyfiles[i]
images = cv2.imread(image_path,
cv2.IMREAD_GRAYSCALE)
Training_Data.append(np.asarray(images,dtype=np.uint8))
Labels.append(i)
2) You have 2 indexes, but use only 1. Is files defined, or is it extraneous? If it is extra, what you think is going into i, may actually be going into files.
In any case, there is a variable that has been assigned a None value. You need to find out which one.
Related
I'm trying to preprocess video frames for anomaly event detection. The model is already trained but I can't figure out the issue with the following code (I'm a beginner). Please help with this respected developers.
def Fit_Preprocessing(path: object, frames_ext: object) -> object:
if frames_ext is None:
raise TypeError(
'Invalid Value for argument `frames_ext`, it cannot be None. Give proper extensions of the frames e.g: `.tif` or `.png` etc!')
print('\n\nProcessing Images in this Dataset Path: {0}\n'.format(path))
file_names: List[Union[str, List[str]]]
onlyfiles, file_names, dirs = ReadFileNames(path, frames_ext)
img_list = [1, 2, 3, 4]
for img in tqdm(range(len(onlyfiles))):
images = onlyfiles[img]
count = 0
for images in onlyfiles[img]:
img.split('/')
img_name = dirs[i] + '_' + file_names[i][count]
write_path = 'ProcessedImages/' + path.split('/')[1]
gray = ProcessImg(img_name, read_path=img, write=True,
write_path=write_path, res_shape=(227, 227))
img_list.append(gray)
count += 1
return img_list
Getting this error:
Processing Images in this Dataset Path: C:/Users/Public/Downloads/Surveillance with deep learning/Datasets/UCSD_Anomaly_Dataset.v1p2/UCSDped1/Test
0%| | 0/47 [00:00<?, ?it/s]
Traceback (most recent call last):
File "C:/Users/Public/Downloads/Surveillance-with-deep-learning/preprocessing.py", line 171, in <module>
img_list: object = Fit_Preprocessing(path, frames_ext='.Fit')
File "C:/Users/Public/Downloads/Surveillance-with-deep-learning/preprocessing.py", line 154, in Fit_Preprocessing
for images in onlyfiles[img]:
TypeError: 'int' object is not iterable
Process finished with exit code 1
I tried using images = img_list to fix the loop but it did not work
The reason you are getting an error is because in the for loop:
for images in onlyfiles[img]:
You are getting the value using the index to access it, and onlyfiles[img] will, according to your code, return an int value. Since I don't know what you are clearly doing, my suggestion is to turn onlyfiles[img] into a list, so it iterates only through one thing or more, using:
for images in [onlyfiles[img]]:
Example:
my_int = 123
for i in my_int:
print(i)
Gets the error:
Traceback (most recent call last):
File "main.py", line 2, in <module>
for i in my_int:
TypeError: 'int' object is not iterable
So if you turn it into a list:
my_int = 123
for i in [my_int]:
print(i)
Gives:
123
Or if you want to iterate through the digits, turn it into a string:
my_int = 123
for i in str(my_int):
print(i)
Gives:
1
2
3
In my code I need to convert an image to a numpy array, then from an array to a list. After performing some changes to the list I need to convert back to an image but I get this error
Traceback (most recent call last):
File "/home/owner/anaconda3/envs/proj1/lib/python3.7/site-packages/PIL/Image.py", line 2714, in fromarray
mode, rawmode = _fromarray_typemap[typekey]
KeyError: ((1, 1, 3), '<i8')
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/owner/PycharmProjects/arrays3/test.py", line 31, in <module>
im = Image.fromarray(b)
File "/home/owner/anaconda3/envs/proj1/lib/python3.7/site-packages/PIL/Image.py", line 2716, in fromarray
raise TypeError("Cannot handle this data type: %s, %s" % typekey)
TypeError: Cannot handle this data type: (1, 1, 3), <i8
I know that the error is occuring due to the transition from array to list and back but I'm not sure why. Here is some code that produces the same error but makes no modifications to the contents of the image data, as the print statement returns true.
im = Image.open("wp2793461-windows-98-wallpaper-pack.jpg")
a = np.asarray(im)
lst = a.tolist()
b = np.asarray(lst)
print(np.array_equal(a, b))
im = Image.fromarray(b)
im.save("new.jpg")
Nice conundrum! I was looking at what the differences between a and b are, and found that numpy's dtype is different for both.
>>> print(a.dtype)
uint8
>>> print(b.dtype)
int64
If you create b in the following way, it works again:
b = np.asarray(lst, dtype=a.dtype)
I am trying to implement my own version of the MatLab function imhmin() in Python using OpenCV and (naturally) NumPy. If you are not familiar with this MatLab function, it's extremely useful for segmentation. MatLab's documentation can explain it much better than I can:
https://it.mathworks.com/help/images/ref/imhmin.html
Here is what I have so far:
(For the sake of keeping this short, I did not include the local_min function. It takes one image parameter and returns an image of the same size where local minima are 1s and everything else is 0.)
from volume import show
import cv2
import numpy
def main():
arr = numpy.array( [[5,5,5,5,5,5,5],
[5,0,3,1,4,2,5],
[5,5,5,5,5,5,5]] ) + 1
res = imhmin(arr, 3)
print(res)
def imhmin(src, h):
# TODO: speed up function by cropping image
edm = src.copy()
# d is the domain / all values contained in the array
d = numpy.unique(edm)
# for the index of each local minima (sorted gtl)
indices = numpy.nonzero(local_min(edm)) # get indices
indices = numpy.dstack((indices[0], indices[1]))[0].tolist() # zip
# sort based on the value of edm[] at that index
indices.sort(key = lambda _: edm[_[0],_[1]], reverse = True)
for (x,y) in indices:
start = edm[x,y] # remember original value of minima
# for each in a list of heights greater than the starting height
for i in range(*numpy.where(d==edm[x,y])[0], d.shape[0]-1):
# prevent exceeding target height
step = start + h if (d[i+1] - start > h) else d[i+1]
#-------------- WORKS UNTIL HERE --------------#
# complete floodFill syntax:
# cv2.floodFill(image, mask, seed, newVal[, loDiff[, upDiff[, flags]]]) → retval, rect
# fill UPWARD onto image (and onto mask?)
cv2.floodFill(edm, None, (y,x), step, 0, step-d[i], 4)
# fill DOWNWARD NOT onto image
# have you overflowed?
if __name__ == "__main__":
main()
Which works fine until it gets to the floodfill line. It barks this error back:
Traceback (most recent call last):
File "edm.py", line 94, in <module>
main()
File "edm.py", line 14, in main
res = imhmin(arr, 3)
File "edm.py", line 66, in imhmin
cv2.floodFill(edm, None, (y,x), step, 0, step-d[i], 4)
TypeError: Layout of the output array image is incompatible with cv::Mat (step[ndims-1] != elemsize or step[1] != elemsize*nchannels)
At first I thought maybe the way I laid out the parameters was wrong because of the stuff about step in the traceback, but I tried changing that variable's name and have come to the conclusion that step is some variable name in OpenCV's code. It's talking about the output array, and I'm not using a mask, so something must be wrong with the array edm.
I can suppress this error by replacing the floodfill line with this one:
cv2.floodFill(edm.astype(numpy.double), None, (y,x), step, 0, step-d[i], 4)
The difference being that I am typecasting the numpy array to a float array. Then I am left with this error:
Traceback (most recent call last):
File "edm.py", line 92, in <module>
main()
File "edm.py", line 14, in main
res = imhmin(arr, 3)
File "edm.py", line 64, in imhmin
cv2.floodFill(edm.astype(numpy.double), None, (y,x), step, 0, step-d[i], 4)
TypeError: Scalar value for argument 'newVal' is not numeric
This is where I started suspecting something was seriously wrong, because step is "obviously" going to be an integer here (maybe it isn't obvious, but I did try printing it and it looks like it's just an integer, not an array of one integer or anything weird like that).
To entertain the error message, I typecast the newVal parameter to a float. I got pretty much the exact same error message about the upDiff parameter, so I just typecast that too, resulting in this line of code:
cv2.floodFill(edm.astype(numpy.double), None, (y,x), float(step), 0, float(step-d[i]), 4)
I know this isn't how I want to be doing things, but I just wanted to see what would happen. What happened was I got this scary looking error:
Traceback (most recent call last):
File "edm.py", line 92, in <module>
main()
File "edm.py", line 14, in main
res = imhmin(arr, 3)
File "edm.py", line 64, in imhmin
cv2.floodFill(edm.astype(numpy.double), None, (y,x), float(step), 0, float(step-d[i]), 4)
cv2.error: OpenCV(3.4.2) /opt/concourse/worker/volumes/live/9523d527-1b9e-48e0-7ed0-a36adde286f0/volume/opencv-suite_1535558719691/work/modules/imgproc/src/floodfill.cpp:587: error: (-210:Unsupported format or combination of formats) in function 'floodFill'
I don't even know where to start with this. I've used OpenCV's floodfill function many times before and have never run into problems like this. Can anyone provide any insight?
Thanks in advance
Antonio
I want to list all the sub-directories of a directory but it throws type error
TRAIN_PATH_ARRAY=['New folder/train/']
TEST_PATH_ARRAY=['New folder/test/']
train_ids = next(os.walk(TRAIN_PATH_ARRAY))[1]
test_ids = next(os.walk(TEST_PATH_ARRAY))[1]
np.random.seed(10)
Output:
TypeError Traceback (most recent call last)
<ipython-input-11-a1a31c46fb70> in <module>
----> 1 train_ids = next(os.walk(TRAIN_PATH_ARRAY))[1]
2 test_ids = next(os.walk(TEST_PATH_ARRAY))[1]
3 np.random.seed(10)
~\Anaconda3\lib\os.py in walk(top, topdown, onerror, followlinks)
334
335 """
--> 336 top = fspath(top)
337 dirs = []
338 nondirs = []
TypeError: expected str, bytes or os.PathLike object, not list
Like the error message rather plainly says, the argument to os.walk() should be a str (or a pathlib path), not a list.
It's not really clear what you hope for the code to actually accomplish. Extracting just the second element out of the first result from os.walk() is not correct because it returns a file names relative to the starting directory. But if that's what you are after, maybe try
TRAIN_PATH='New folder/train/'
TEST_PATH='New folder/test/'
train_ids = [os.path.join(TRAIN_PATH, x) for x in next(os.walk(TRAIN_PATH))[1])]
test_ids = [os.path.join(TEST_PATH, x) for x in next(os.walk(TEST_PATH))[1])]
If indeed you want to traverse an array, I'm afraid you will need to explain the intention of your code in more detail.
I am trying to recreate some of the work from the blog posting http://sarvamblog.blogspot.com/2013/04/clustering-malware-corpus.html
import itertools
import glob
import numpy,scipy, os, array
from scipy.misc import imsave
for filename in list(glob.glob('file/*.file')):
f = open(filename,'rb');
#just want to make sure I get the right file'
print filename
ln = os.path.getsize(filename); # length of file in bytes
width = 256;
rem = ln%width;
a = array.array("B"); # uint8 array
a.fromfile(f,ln-rem);
f.close();
g = numpy.reshape(a,(len(a)/width,width));
g = numpy.uint8(g);
fpng = filename + ".png"
# make sure the png process and everything else is going'
print fpng
scipy.misc.imsave(fpng,g);`
And although this runs great on 1 or 2 files, I run into problems on once I expand to dozens
Traceback (most recent call last):
File "<stdin>", line 14, in <module>
File "/usr/lib/python2.7/dist-packages/scipy/misc/pilutil.py", line 120, in imsave
im = toimage(arr)
File "/usr/lib/python2.7/dist-packages/scipy/misc/pilutil.py", line 183, in toimage
image = Image.fromstring('L',shape,bytedata.tostring())
File "/usr/lib/python2.7/dist-packages/PIL/Image.py", line 1797, in fromstring
im.fromstring(data, decoder_name, args)
File "/usr/lib/python2.7/dist-packages/PIL/Image.py", line 590, in fromstring
d.setimage(self.im)
ValueError: tile cannot extend outside image
I assume that my issue is with not either A: closing the scipy.misc.imsave or B: not resetting the arrarys. Any help would be greatly appreciated
Managed to figure it out with a try/except loop. Once I did that I was able to determine that only certain files were canceling out. These files were extremely small (125 bytes). My assumption is that they were too small to create all the info needed for scipy
im.crop(box) ⇒ image
The box is a 4-tuple defining the left, upper, right, and lower pixel coordinate.
when lower is small than upper in my code,this error has happened.