Меню

Nonetype object has no attribute shape ошибка

nonetype_output

Each week I receive and respond to at least 2-3 emails and 3-4 blog post comments regarding NoneType errors in OpenCV and Python.

For beginners, these errors can be hard to diagnose — by definition they aren’t very informative.

Since this question is getting asked so often I decided to dedicate an entire blog post to the topic.

While NoneType errors can be caused for a nearly unlimited number of reasons, in my experience, both as a computer vision developer and chatting with other programmers here on PyImageSearch, in over 95% of the cases, NoneType errors in OpenCV are caused by either:

  1. An invalid image path passed to cv2.imread .
  2. A problem reading a frame from a video stream/video file via cv2.VideoCapture and the associated .read method.

To learn more about NoneType errors in OpenCV (and how to avoid them), just keep reading.

Looking for the source code to this post?

Jump Right To The Downloads Section

In the first part of this blog post I’ll discuss exactly what NoneType errors are in the Python programming language.

I’ll then discuss the two primary reasons you’ll run into NoneType errors when using OpenCV and Python together.

Finally, I’ll put together an actual example that not only causes a NoneType error, but also resolves it as well.

What is a NoneType error?

When using the Python programming language you’ll inevitably run into an error that looks like this:

AttributeError: 'NoneType' object has no attribute ‘something’

Where something can be replaced by whatever the name of the actual attribute is.

We see these errors when we think we are working with an instance of a particular Class or Object, but in reality we have the Python built-in type None .

As the name suggests, None represents the absence of a value, such as when a function call returns an unexpected result or fails entirely.

Here is an example of generating a NoneType error from the Python shell:

>>> foo = None
>>> foo.bar = True
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'bar'
>>>

Here I create a variable named foo and set it to None .

I then try to set the bar attribute of foo to True , but since foo is a NoneType object, Python will not allow this — hence the error message.

Two reasons for 95% of OpenCV NoneType errors

When using OpenCV and Python bindings, you’re bound to come across NoneType errors at some point.

In my experience, over 95% of the time these NoneType errors can be traced back to either an issue with cv2.imread or cv2.VideoCapture .

I have provided details for each of the cases below.

Case #1: cv2.imread

If you are receiving a NoneType error and your code is calling cv2.imread , then the likely cause of the error is an invalid file path supplied to cv2.imread .

The cv2.imread function does not explicitly throw an error message if you give it an invalid file path (i.e., a path to a nonexistent file). Instead, cv2.imread will simply return None .

Anytime you try to access an attribute of a None image loaded from disk via cv2.imread you’ll get a NoneType error.

Here is an example of trying to load a nonexistent image from disk:

$ python
>>> import cv2
>>> path = "path/to/image/that/does/not/exist.png"
>>> image = cv2.imread(path)
>>> print(image.shape)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'shape'

As you can see, cv2.imread gladly accepts the image path (even though it doesn’t exist), realizes the image path is invalid, and returns None . This is especially confusing for Python programmers who are used to these types of functions throwing exceptions.

As an added bonus, I’ll also mention the AssertionFailed exception.

If you try to pass an invalid image (i.e., NoneType image) into another OpenCV function, Python + OpenCV will complain that the image doesn’t have any width, height, or depth information — and how could it, the “image” is a None object after all!

Here is an example of an error message you might see when loading a nonexistent image from disk and followed by immediately calling an OpenCV function on it:

>>> import cv2
>>> path = "path/to/image/that/does/not/exist.png"
>>> image = cv2.imread(path)
>>> gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
OpenCV Error: Assertion failed (scn == 3 || scn == 4) in cvtColor, file /tmp/opencv20150906-42178-3d0iam/opencv-2.4.12/modules/imgproc/src/color.cpp, line 3739
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
cv2.error: /tmp/opencv20150906-42178-3d0iam/opencv-2.4.12/modules/imgproc/src/color.cpp:3739: error: (-215) scn == 3 || scn == 4 in function cvtColor

>>>

These types of errors can be harder to debug since there are many reasons why an AssertionError could be thrown. But in most cases, your first step should be be ensuring that your image was correctly loaded from disk.

A final, more rare problem you may encounter with cv2.imread is that your image does exist on disk, but you didn’t compile OpenCV with the given image I/O libraries installed.

For example, let’s say you have a .JPEG file on disk and you knew you had the correct path to it.

You then try to load the JPEG file via cv2.imread and notice a NoneType or AssertionError .

How can this be?

The file exists!

In this case, you likely forgot to compile OpenCV with JPEG file support enabled.

In Debian/Ubuntu systems, this is caused by a lack of libjpeg being installed.

For macOS systems, you likely forgot to install the jpeg library via Homebrew.

To resolve this problem, regardless of operating system, you’ll need to re-compile and re-install OpenCV. Please see this page for more details on how to compile and install OpenCV on your particular system.

Case #2: cv2.VideoCapture and .read

Just like we see NoneType errors and AssertionError exceptions when using cv2.imread , you’ll also see these errors when working with video streams/video files as well.

To access a video stream, OpenCV uses the cv2.VideoCapture which accepts a single argument, either:

  1. A string representing the path to a video file on disk.
  2. An integer representing the index of a webcam on your computer.

Working with video streams and video files with OpenCV is more complex than simply loading an image via cv2.imread , but the same rules apply.

If you try to call the .read method of an instantiated cv2.VideoCapture (regardless if it’s a video file or webcam stream) and notice a NoneType error or AssertionError , then you likely have a problem with either:

  1. The path to your input video file (it’s probably incorrect).
  2. Not having the proper video codecs installed, in which case you’ll need to install the codecs, followed by re-compiling and re-installing OpenCV (see this page for a complete list of tutorials).
  3. Your webcam not being accessible via OpenCV. This could be for any number of reasons, including missing drivers, an incorrect index passed to cv2.VideoCapture , or simply your webcam is not properly attached to your system.

Again, working with video files is more complex than working with simple image files, so make sure you’re systematic in resolving the issue.

First, try to access your webcam via a separate piece of software than OpenCV.

Or, try to load your video file in a movie player.

If both of those work, you likely have a problem with your OpenCV install.

Otherwise, it’s most likely a codec or driver issue.

An example of creating and resolving an OpenCV NoneType error

To demonstrate a NoneType error in action I decided to create a highly simplified Python + OpenCV script that represents what you might see elsewhere on the PyImageSearch blog.

Open up a new file, name it display_image.py , and insert the following code:

# import the necessary packages
import argparse
import cv2

# construct the argument parse and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image", required=True,
	help="path to the image file")
args = vars(ap.parse_args())

# load the image from disk and display the width, height,
# and depth
image = cv2.imread(args["image"])
(h, w, d) = image.shape
print("w: {}, h: {}, d: {}".format(w, h, d))

# show the image
cv2.imshow("Image", image)
cv2.waitKey(0)

All this script does is:

  • Parse command line arguments.
  • (Attempts to) load an image from disk.
  • Prints the width, height, and depth of the image to the terminal.
  • Displays the image to our screen.

For most Python developers who are familiar with the command line, this script won’t give you any trouble.

But if you’re new to the command line and are unfamiliar/uncomfortable with command line arguments, you can easily run into a NoneType error if you’re not careful.

How, you might say?

The answer lies in not properly using/understanding command line arguments.

Over the past few years of running this blog, I’ve seen many emails and blog post comments from readers who are trying to modify the .add_argument function to supply the path to their image file.

DON’T DO THIS — you don’t have to change a single line of argument parsing code.

Instead, what you should do is spend the next 10 minutes reading through this excellent article that explains what command line arguments are and how to use them in Python:

This is required reading if you expect to follow tutorials here on the PyImageSearch blog.

Working with the command line, and therefore command line arguments, are a big part of what it means to be a computer scientist — a lack of command line skills is only going to harm you. You’ll thank me later.

Going back to the example, let’s check the contents of my local directory:

$ ls -l
total 800
-rw-r--r--  1 adrianrosebrock  staff     541 Dec 21 08:45 display_image.py
-rw-r--r--  1 adrianrosebrock  staff  403494 Dec 21 08:45 jemma.png

As we can see, I have two files:

  1. display_image.py : My Python script that I’ll be executing shortly.
  2. jemma.png : The photo I’ll be loading from disk.

If I execute the following command I’ll see the jemma.png image displayed to my screen, along with information on the dimensions of the image:

$ python display_image.py --image jemma.png
w: 376, h: 500, d: 3

Figure 1: Loading and displaying an image to my screen with OpenCV and Python.

Figure 1: Loading and displaying an image to my screen with OpenCV and Python.

However, let’s try to load an image path that does not exist:

$ python display_image.py --image i_dont_exist.png
Traceback (most recent call last):
  File "display_image.py", line 17, in <module>
    (h, w, d) = image.shape
AttributeError: 'NoneType' object has no attribute 'shape'

Sure enough, there is our NoneType  error.

In this case, it was caused because I did not supply a valid image path to cv2.imread .

What’s next? I recommend PyImageSearch University.

Course information:
64 total classes • 68 hours of on-demand code walkthrough videos • Last updated: January 2023
★★★★★ 4.84 (128 Ratings) • 15,800+ Students Enrolled

I strongly believe that if you had the right teacher you could master computer vision and deep learning.

Do you think learning computer vision and deep learning has to be time-consuming, overwhelming, and complicated? Or has to involve complex mathematics and equations? Or requires a degree in computer science?

That’s not the case.

All you need to master computer vision and deep learning is for someone to explain things to you in simple, intuitive terms. And that’s exactly what I do. My mission is to change education and how complex Artificial Intelligence topics are taught.

If you’re serious about learning computer vision, your next stop should be PyImageSearch University, the most comprehensive computer vision, deep learning, and OpenCV course online today. Here you’ll learn how to successfully and confidently apply computer vision to your work, research, and projects. Join me in computer vision mastery.

Inside PyImageSearch University you’ll find:

  • 64 courses on essential computer vision, deep learning, and OpenCV topics
  • 64 Certificates of Completion
  • 68 hours of on-demand video
  • Brand new courses released regularly, ensuring you can keep up with state-of-the-art techniques
  • Pre-configured Jupyter Notebooks in Google Colab
  • ✓ Run all code examples in your web browser — works on Windows, macOS, and Linux (no dev environment configuration required!)
  • ✓ Access to centralized code repos for all 500+ tutorials on PyImageSearch
  • Easy one-click downloads for code, datasets, pre-trained models, etc.
  • Access on mobile, laptop, desktop, etc.

Click here to join PyImageSearch University

Summary

In this blog post I discussed NoneType  errors and AssertionError  exceptions in OpenCV and Python.

In the vast majority of these situations, these errors can be attributed to either the cv2.imread  or cv2.VideoCapture  methods.

Whenever you encounter one of these errors, make sure you can load your image/read your frame before continuing. In over 95% of circumstances, your image/frame was not properly read.

Otherwise, if you are using command line arguments and are unfamiliar with them, there is a chance that you aren’t using them properly. In that case, make sure you educate yourself by reading this tutorial on command line arguments — you’ll thank me later.

Anyway, I hope this tutorial has helped you in your journey to OpenCV mastery!

If you’re just getting started studying computer vision and OpenCV, I would highly encourage you to take a look at my book, Practical Python and OpenCV, which will help you grasp the fundamentals.

Otherwise, make sure you enter your email address in the form below to be notified when future blog posts and tutorials are published!

Download the Source Code and FREE 17-page Resource Guide

Enter your email address below to get a .zip of the code and a FREE 17-page Resource Guide on Computer Vision, OpenCV, and Deep Learning. Inside you’ll find my hand-picked tutorials, books, courses, and libraries to help you master CV and DL!

Hello;
I‘m running the real_time_object_detection program,and the problem is :D:python3.5.2Modelobject-detection-deep-learning>python real_time_object_detection.py —prototxt=MobileNetSSD_deploy.prototxt.txt —model=MobileNetSSD_deploy.caffemodel
[INFO] loading model…
[INFO] starting video stream…
Traceback (most recent call last):
File «real_time_object_detection.py», line 44, in
frame = imutils.resize(frame, width=400)
File «C:Anaconda3libsite-packagesimutilsconvenience.py», line 69, in resize
(h, w) = image.shape[:2]
AttributeError: ‘NoneType’ object has no attribute ‘shape’

the code is:

import the necessary packages

from imutils.video import VideoStream
from imutils.video import FPS
import numpy as np
import argparse
import imutils
import time
import cv2

construct the argument parse and parse the arguments

ap = argparse.ArgumentParser()
ap.add_argument(«-p», «—prototxt», required=True,
help=»path to Caffe’deploy’prototxt file»)
ap.add_argument(«-m», «—model», required=True,
help=»path to Caffe pre-trained model»)
ap.add_argument(«-c», «—confidence», type=float, default=0.2,
help=»minimum probability to filter weak detections»)
args = vars(ap.parse_args())

initialize the list of class labels MobileNet SSD was trained to

detect, then generate a set of bounding box colors for each class

CLASSES = [«background», «aeroplane», «bicycle», «bird», «boat»,
«bottle», «bus», «car», «cat», «chair», «cow», «diningtable»,
«dog», «horse», «motorbike», «person», «pottedplant», «sheep»,
«sofa», «train», «tvmonitor»]
COLORS = np.random.uniform(0, 255, size=(len(CLASSES), 3))

load our serialized model from disk

print(«[INFO] loading model…»)
net = cv2.dnn.readNetFromCaffe(args[«prototxt»], args[«model»])

initialize the video stream, allow the cammera sensor to warmup,

and initialize the FPS counter

print(«[INFO] starting video stream…»)
vs = VideoStream(src=1).start()
time.sleep(2.0)
fps = FPS().start()

loop over the frames from the video stream

while True:
# grab the frame from the threaded video stream and resize it
# to have a maximum width of 400 pixels
frame = vs.read()
frame = imutils.resize(frame, width=400)

# grab the frame dimensions and convert it to a blob
(h, w) = frame.shape[:2]
blob = cv2.dnn.blobFromImage(frame, 0.007843, (300, 300), 127.5)

# pass the blob through the network and obtain the detections and
# predictions
net.setInput(blob)
detections = net.forward()

loop over the detections

for i in np.arange(0, detections.shape[2]):
	# extract the confidence (i.e., probability) associated with
	# the prediction
	confidence = detections[0, 0, i, 2]

	# filter out weak detections by ensuring the `confidence` is
	# greater than the minimum confidence
	if confidence > args["confidence"]:
		# extract the index of the class label from the
		# `detections`, then compute the (x, y)-coordinates of
		# the bounding box for the object
		idx = int(detections[0, 0, i, 1])
		box = detections[0, 0, i, 3:7] * np.array([w, h, w, h])
		(startX, startY, endX, endY) = box.astype("int")

		# draw the prediction on the frame
		label = "{}: {:.2f}%".format(CLASSES[idx],
			confidence * 100)
		cv2.rectangle(frame, (startX, startY), (endX, endY),
			COLORS[idx], 2)
		y = startY - 15 if startY - 15 > 15 else startY + 15
		cv2.putText(frame, label, (startX, y),
			cv2.FONT_HERSHEY_SIMPLEX, 0.5, COLORS[idx], 2)

show the output frame

cv2.imshow("Frame", frame)
key = cv2.waitKey(1) & 0xFF

# if the `q` key was pressed, break from the loop
if key == ord("q"):
	break

# update the FPS counter
fps.update()

stop the timer and display FPS information

fps.stop()
print(«[INFO] elapsed time: {:.2f}».format(fps.elapsed()))
print(«[INFO] approx. FPS: {:.2f}».format(fps.fps()))

do a bit of cleanup

cv2.destroyAllWindows()
vs.stop()

may be the problem is it didn’t active the camera when I was running “vs = VideoStream(src=1).start()”?
appreciated for helping me,Thank you.

Вопрос:

Ответ №1

Это означает, что где-то функция, которая должна вернуть изображение, просто вернула None и поэтому не имеет атрибута shape. Пытаться    “print img”
чтобы проверить, нет ли вашего изображения None или фактического numpy-объекта.

Ответ №2

Я столкнулся с той же проблемой сегодня, пожалуйста, проверьте путь к изображению, как указано Cybseccrypt. После прочтения попробуйте распечатать изображение и посмотреть. Если вы получаете значение, это означает, что файл открыт.

Код:

img_src = cv2.imread('/home/deepak/python-workout/box2.jpg',0)
print img_src

Надеюсь это поможет!

Ответ №3

Вероятно, вы получите ошибку, потому что ваш путь к видео может быть неправильным. Убедитесь, что ваш путь полностью прав.

Ответ №4

попытайтесь обработать ошибку, ее ошибку атрибута, данную OpenCV

try:
img.shape
print("checked for shape".format(img.shape))
except AttributeError:
print("shape not found")
#code to move to next frame

Ответ №5

Это связано с тем, что путь к изображению неправильный или имя изображения, которое вы пишете, неверно.

как проверить? сначала попробуйте напечатать изображение с помощью print (img), если оно печатает “Нет”, что означает, что вы указали неверный путь к изображению, исправьте этот путь и повторите попытку.

Ответ №6

Я просто встречаю ту же проблему. Я решаю это путем обновления новейшей версии OpenCV. Это хорошо работает со мной. Надеюсь, с тобой все в порядке.

Ответ №7

форма атрибута ошибки

я использую openCV 3.30, какое обновление версии для решения этой проблемы? я все еще ошибаюсь до сих пор.

Ответ №8

Надеюсь, что это поможет всем, кто сталкивается с той же проблемой

Чтобы точно знать, где произошло, поскольку запущенная программа не упоминает об этом как об ошибке с номером строки

'NoneType' object has no attribute 'shape'

Обязательно добавьте assert после загрузки image/frame

Для изображения

image = cv2.imread('myimage.png')
assert not isinstance(image,type(None)), 'image not found'

Для видео

cap = cv2.VideoCapture(0)

while(cap.isOpened()):

# Capture frame-by-frame
ret, frame = cap.read()
if ret:
assert not isinstance(frame,type(None)), 'frame not found'

Помог мне решить похожую проблему в длинном сценарии

Ответ №9

Я работаю с искусственно созданными изображениями, т.е. я создаю их сам, а затем обучаю их нейронной сети для выполнения определенной задачи.
Итак, я создал эти изображения, сохранил их, но когда я попытался открыть их (с помощью cv2.imread(…)), я получил эту ошибку. Оказалось, что при искусственном сохранении создавалось изображения, которые нужно добавить dtype = np.uint8. Это решило проблему для меня!

Hi all! I need your help regarding the following code. My goal is to read and show the video with a resolution modification.


import cv2 

cap = cv2.VideoCapture("C:/Users/user/Desktop/Foot_Detection/ball_tracking_example.mp4")

def rescale_frame(frame, percent=30): width = int(frame.shape[1] * percent/ 100) height = int(frame.shape[0] * percent/ 100) dim = (width, height) return cv2.resize(frame, dim, interpolation =cv2.INTER_AREA)

if (cap.isOpened() == False): print("Error opening video stream or file")

while (cap.isOpened()): # Capture frame-by-frame ret, frame = cap.read()

frame = rescale_frame(frame, percent=30) if ret == True:

cv2.imshow('Frame', frame)

if cv2.waitKey(25) & 0xFF == ord('q'): break

else: break

cap.release()

cv2.destroyAllWindows()

After executing the above code, the video displayed on my screen till the end. However, I have got the following error:


Traceback (most recent call last):
  File "C:/Users/user/Desktop/Foot_Detection/FootDetection.py", line 24, in <module>
    frame = rescale_frame(frame, percent=30)
  File "C:/Users/user/Desktop/Foot_Detection/FootDetection.py", line 10, in rescale_frame
    width = int(frame.shape[1] * percent/ 100)
AttributeError: 'NoneType' object has no attribute 'shape'
 

I tried to install the codec for mp4 and to the video path is correct.
Could you please assist me in this matter?
Thank you in advance.

2 answers

I am using OpenCV 4.0.1, using raspberry pi 3. Do not put outside of while condition block. And do not used this else: break. Because it will disappeared window. The correct code like this:

import cv2

cap = cv2.VideoCapture("C:/Users/user/Desktop/Foot_Detection/ball_tracking_example.mp4")
def rescale_frame(frame, percent=30):
    width = int(frame.shape[1] * percent/ 100)
    height = int(frame.shape[0] * percent/ 100)
    dim = (width, height)
    return cv2.resize(frame, dim, interpolation =cv2.INTER_AREA)
if (cap.isOpened() == False):
    print("Error opening video stream or file")
while (cap.isOpened()):
    # Capture frame-by-frame
    ret, frame = cap.read()
    frame = rescale_frame(frame, percent=30)
    if ret == True:
        cv2.imshow('Frame', frame)
        if cv2.waitKey(25) & 0xFF == ord('q'):
            break


cap.release()
cv2.destroyAllWindows()

I was able to solve the problem. I just need to figure out how to loop:


import numpy as np
import cv2
cap = cv2.VideoCapture('C:Sample3.mp4')

def rescale_frame(frame, percent=30):

    width = int(frame.shape[1] * percent/ 100)
    height = int(frame.shape[0] * percent/ 100)
    dim = (width, height)
    return cv2.resize(frame, dim, interpolation =cv2.INTER_AREA)

while True:
    ret ,frame = cap.read()
    if type(frame) == type(None):
        break
    frame25 = rescale_frame(frame, percent=25)
    cv2.imshow('frame25',frame25)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
cap.release()
cv2.destroyAllWindows()
 

Question Tools

1 follower

Related questions

No answer to this question. Be the first to respond.

Your answer

Related Questions In Python

  • All categories

  • Apache Kafka
    (84)

  • Apache Spark
    (596)

  • Azure
    (131)

  • Big Data Hadoop
    (1,907)

  • Blockchain
    (1,673)

  • C#
    (141)

  • C++
    (271)

  • Career Counselling
    (1,060)

  • Cloud Computing
    (3,436)

  • Cyber Security & Ethical Hacking
    (147)

  • Data Analytics
    (1,266)

  • Database
    (855)

  • Data Science
    (75)

  • DevOps & Agile
    (3,570)

  • Digital Marketing
    (111)

  • Events & Trending Topics
    (28)

  • IoT (Internet of Things)
    (387)

  • Java
    (1,247)

  • Kotlin
    (8)

  • Linux Administration
    (389)

  • Machine Learning
    (337)

  • MicroStrategy
    (6)

  • PMP
    (423)

  • Power BI
    (516)

  • Python
    (3,188)

  • RPA
    (650)

  • SalesForce
    (92)

  • Selenium
    (1,569)

  • Software Testing
    (56)

  • Tableau
    (608)

  • Talend
    (73)

  • TypeSript
    (124)

  • Web Development
    (3,002)

  • Ask us Anything!
    (66)

  • Others
    (1,838)

  • Mobile Development
    (263)

Join the world’s most active Tech Community!

Welcome back to the World’s most active Tech Community!

Subscribe to our Newsletter, and get personalized recommendations.

Already have an account? Sign in.

Forum rules

Read the FAQs and search the forum before posting a new topic.

This forum is for reporting errors with the Training process. If you want to get tips, or better understand the Training process, then you should look in the Training Discussion forum.

Please mark any answers that fixed your problems so others can find the solutions.

User avatar

poldned34

Posts: 6
Joined: Wed May 12, 2021 10:00 am

Answers: 1

Has thanked: 3 times
Been thanked: 1 time

‘NoneType’ object has no attribute ‘shape’

Hi everyone.
Recently become supporter on patreon and updated to the latest version. Before an update I successfully used some of the old versions (not the one released August 2020, but previous one).

The problem — every 30-60 minutes my training process crash with [‘NoneType’ object has no attribute ‘shape’] error.
Except this, looks like model is learning as it should.

I would be really thankful for any help.

I tried:

  1. Recreate model from scratch
  2. To use other model plugin (using Phaze-A, tried switch to unbalanced).
  3. Manually checked all of my faces (just visual check that images are not obviously corrupted).
  4. Split all my A and B faces to 4 folders. Then, tried to run model from scratch with one half of faces firstly, then to run new model with other half of faces.
  5. Reextracted all of my faces (using old alignments)

None of this resolved my problem.

Aligments of face B was updated from old faceswap version. Face A alignments are new.
I tried to find bad faces in log file by checking faces that was loaded in model just before crash, but, it seems that its always different faces, and they all look completely valid.

I don’t see how to upload a log file here on the forum, so I uploaded it here: https://dropfiles.org/XOJnqKxq
Let me know if I need to upload it some other way.

User avatar

torzdf

Posts: 2198
Joined: Fri Jul 12, 2019 12:53 am

Answers: 141

Has thanked: 108 times
Been thanked: 501 times

Re: ‘NoneType’ object has no attribute ‘shape’

Post

by torzdf » Thu May 13, 2021 11:31 pm

First up, many thanks for your support, it is hugely appreciated. Be sure to check out our Discord as there are exclusive supporter areas there.

There is indeed an issue with at least one of your training images. Unfortunately the issue you have hit is inside the code which is meant to tell you which image is causing the issue :ugeek:

I have just pushed an update to hopefully fix this.

If you go Help > Update Faceswap. Close the app, re-open, it will hopefully tell you where the issue lies.

My word is final

User avatar

poldned34

Posts: 6
Joined: Wed May 12, 2021 10:00 am

Answers: 1

Has thanked: 3 times
Been thanked: 1 time

Re: ‘NoneType’ object has no attribute ‘shape’

Post

by poldned34 » Fri May 14, 2021 10:25 am

Logs become morre informative, thank you. I found few ‘bad’ faces and removed them.

But, Is it possible that update break something?
I have new problem.
Training crash every 10-15 minutes with this error:
05/14/2021 13:15:05 ERROR There are mismatched image sizes in the folder ‘F:cf_new’. All training images for each side must have the same dimensions.
05/14/2021 13:15:05 ERROR The batch that failed contains the following files:
05/14/2021 13:15:05 ERROR [’10_070801_0.png (1024px)’, <class ‘NoneType’>, ‘7_029351_0.png (1024px)’, ’12_011101_0.png (1024px)’].

All my images are 1024×1024, I rechecked this. And I never faced this error before yesteray update.
No logs file attached, since this error don’t generate crash reports.

User avatar

torzdf

Posts: 2198
Joined: Fri Jul 12, 2019 12:53 am

Answers: 141

Has thanked: 108 times
Been thanked: 501 times

Re: ‘NoneType’ object has no attribute ‘shape’

Post

by torzdf » Fri May 14, 2021 10:59 am

The image size isn’t the issue, some of your images are failing to load (maybe corruption of some kind?).

The update was meant to say which image fails to load, but I managed to omit it.

Just pushed an update which should lead you to the problematic image.

My word is final

User avatar

poldned34

Posts: 6
Joined: Wed May 12, 2021 10:00 am

Answers: 1

Has thanked: 3 times
Been thanked: 1 time

Re: ‘NoneType’ object has no attribute ‘shape’

Post

by poldned34 » Fri May 14, 2021 1:06 pm

Ok, thank you for all your help.

My current idea is that my hdd with image sets slowly started to become corrupted.
This hdd is pretty old, so there is good chance that it’s time has come.

Don’t see other explanation why so many images become corrupted.

User avatar

torzdf

Posts: 2198
Joined: Fri Jul 12, 2019 12:53 am

Answers: 141

Has thanked: 108 times
Been thanked: 501 times

Re: ‘NoneType’ object has no attribute ‘shape’

Post

by torzdf » Fri May 14, 2021 1:08 pm

If you have confirmed that the images are corrupted, then we’re golden (well, you aren»t, but you know what I mean).

If you can’t find an issue with the images, then feel free to DM me one of the «corrupted» images so I can see if there is an issue with the code.

My word is final

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Npm err a complete log of this run can be found in вылетает ошибка
  • Np 41772 1 ошибка ps4 как исправить на русском