I'm taking pictures with OpenCV library:
def display_frame(self, frame, dt):
texture = Texture.create(size=(frame.shape[1], frame.shape[0]), colorfmt='bgr')
texture.blit_buffer(frame.tobytes(order=None), colorfmt='bgr', bufferfmt='ubyte')
texture.flip_vertical()
self.image.texture = texture
cv2.imwrite('/home/mark/frontend/picture_taken.jpg', self.image)
cam.release()
cv2.destroyAllWindows()
The above throws:
cv2.imwrite('/home/mark/frontend/picture_taken.jpg', self.image)
TypeError: Expected Ptr<cv::UMat> for argument 'img'
I'm not including all parts of the code but the above is giving you idea what kind
of image I'm trying to write on disk. On GitHub I found that this error is usually thrown when we try to write an image that we passed in in a wrong form. In some cases this can
be solved by including img = numpy.array(self.image) right above the line where I write the image. However that didn't work for me.
How this can be fixed ?
Hi this is just a guess but from my own experience i think your image variable is a None type. Can you try and print out if your self.image has any value
Related
I am quite confused cause when I try to save the resized version of an image it says 'AttributeError: 'NoneType' object has no attribute 'save''.
I looked over the internet and also to this question: Python Pillow's thumbnail method returning None but i already used the save function so i don't get why it doesn't work.
Here's my code:
from PIL import Image
imgg = Image.open('cropped.tif')
new_image = imgg.thumbnail((400, 400))
new_image.save('thumbnail_400.tif')
I bet it's something stupid but i can't see what it is. I appreciate any help.
thumbnail() is an extension method without a return object. The new_image variable will stay None in your case. You need to do this.
from PIL import Image
imgg = Image.open('cropped.tif')
imgg.thumbnail((400, 400))
imgg.save('thumbnail_400.tif')
What I'm trying to do: Since I'm still quite new to image generation using the PIL library, I decided to experiment with putting images on top of gifs. There were not a lot of proper tutorials or references I could use.
What's going wrong: More often than not, the gif would not be generated. This would give the error IndexError: bytearray index out of range which I'm not sure how to fix. However, sometimes the gif would be generated, but there would be some errors. I have included some of these gifs below.
The code:
#client.command()
async def salt(ctx, user:discord.Member=None):
if user == None:
user = ctx.author
animated_gif = Image.open("salty.gif")
response = requests.get(user.avatar_url)
background = Image.open(BytesIO(response.content))
all_frames = []
# background = background.resize((500, 500))
for gif_frame in ImageSequence.Iterator(animated_gif):
# duplicate background image
new_frame = background.copy()
# need to convert from `P` to `RGBA` to use it in `paste()` as mask for transparency
gif_frame = gif_frame.convert('RGBA')
# paste on background using mask to get transparency
new_frame.paste(gif_frame, mask=gif_frame)
all_frames.append(new_frame)
# save all frames as animated gif
all_frames[0].save("image.gif", save_all=True, append_images=all_frames[1:], duration=50, loop=0)
This is the gif I am using:
Unfortunately animated GIF support in PIL is faulty, and hard to work with at all. The images you are showing suffer from the layers sharing the palette information with the background layer, so they have some of their colors distorted.
I don't know if there is a way to control the palette information for each frame using PIL.
If you want to generate GIFs progamaticaly using Python, I'd, for now, recommend that you use the GIMP Image editor - there you can build your image, either interactively using the program, or programaticaly, using the Python console, and just call the "save as gif" function (pdb.file_gif_save2).
(I will take a look at PILs exact capabilities, and check if I can extend the answer on proper handling of transparency - otherwise, GIMP is the way to go)
Getting the error bellow in the code
TypeError: 'NoneType' object is not subscriptable
line : crop_img = img[70:300, 70:300]
Can anyone please help me with this?
thanks a lot
img_dofh = cv2.imread("D.png",0)
ret, img = cap.read()
cv2.rectangle(img,(60,60),(300,300),(255,255,2),4) #outer most rectangle
crop_img = img[70:300, 70:300]
crop_img_2 = img[70:300, 70:300]
grey = cv2.cvtColor(crop_img, cv2.COLOR_BGR2GRAY)
You don't show where your img variable comes from. But somehow it is None instead of containing image data.
Often this happens when you write a function that is supposed to return a valid object for img, but you forget to include a return statement in the function, so it automatically returns None instead.
Check the code that creates img.
UPDATE
Responding to your code posting:
It would be helpful if you could provide a minimal, reproducible example. That might look something like this:
import cv2
cap = cv2.VideoCapture(0)
if cap.isOpened():
ret, img = cap.read()
if img is None:
print("img was not returned.")
else:
crop_img = img[70:300, 70:300]
print(crop_img) # should show an array of image data
Looking at the documentation, it appears that your camera may not have grabbed any frames by the time you reach this point in your code. The documentation says "If no frames has been grabbed (camera has been disconnected, or there are no more frames in video file), the methods return false and the functions return NULL pointer." I would bet that the .read() function is returning a NULL pointer, which gets converted to None when it is sent back to Python.
Unfortunately, since no one else has your particular camera setup, other people may have trouble reproducing your problem.
The code above works fine on my MacBook Pro, but I have to give Terminal permission to use the camera the first time I try it. Have you tried restarting your terminal app? Does your program have access to the camera?
im trying to implement the GSOC background subtractor from openCV.
fgbg = cv.bgsegm_BackgroundSubtractorGSOC()
fgmask = fgbg.apply(frame)
but this gives me following error:
fgmask = fgbg.apply(frame)
TypeError: Incorrect type of self (must be 'bgsegm_BackgroundSubtractorGSOC' or its derivative)
and
fgmask = cv.bgsegm_BackgroundSubtractorGSOC.apply(frame)
gives me this error:
fgmask = cv.bgsegm_BackgroundSubtractorGSOC.apply(frame)
TypeError: descriptor 'apply' requires a 'cv2.bgsegm_BackgroundSubtractorGSOC' object but received a 'numpy.ndarray'
The documentation for .apply() says i only need to supply an inputarray (the frame), the output location and the learning rate. Changing .apply(frame) to .apply(frame, output, -1) does not fix the error
how do i correctly implement a bgsegm_BackgroundSubtractorGSOC object and use it on my image?
i read this post but it seems i am failing a step before that already
GSOC and the other background subtraction methods (other than MOG2 and KNN) are located in the extra modules and require the opencv-contrib library to be installed.
Once it is installed, the module can be used by writing:
backSub = cv.bgsegm.createBackgroundSubtractorGSOC()
i'm trying to save an image that is generated during runtime. this works fine for wx.BITMAP_TYPE_JPEG and ..._PNG but fails for wx.BITMAP_TYPE_BMP as well as for ..._GIF.
here's the code:
imgName = 'test.png'
imgType = wx.BITMAP_TYPE_BMP
img = wx.EmptyImage(width, height)
[...]
img.SaveFile(imgName, imgType)
i've also tried to initialize other handlers via wx.InitAllImageHandlers() but that doesn't work either.
.SaveFile(...) keeps returning False and the generated bmp has the size of 0 bytes although the image should contain data.
is there anything wrong with my code or might there be other issues?
thanks in advance