How to load Textures in Pyglet and Ratcave - python-3.x

I am making a simple OpenGL 3.3 OBJ viewer in Python using the modules Pyglet and Ratcave. I want to load a textured sphere I made in Blender. While my Pyglet/Ratcave OBJ viewer loads untextured OBJ files, when I add textures to my project, I get this error and the program fails to load:
ValueError: could not convert string to float: 'textures'
What does this mean?
I got a different error when I tried to import textures from my OneDrive folder and use them in my Blender project. When I put the textures in the same folder as the script and OBJ/MTL files, it got rid of that error, but now I can't load the textures because, for whatever reason, Ratcave needs to convert the textures to a float and it can't do that.
import pyglet
import ratcave as rc
import time
window = pyglet.window.Window()
def update(dt):
pass
pyglet.clock.schedule(update)
# Insert filename into WavefrontReader
obj_filename = 'Textured Sphere Eevee.obj'
obj_reader = rc.WavefrontReader(obj_filename)
# Check which meshes can be found inside the Wavefront file, and extract it into a Mesh object for rendering
print(obj_reader.bodies.keys())
Sphere = obj_reader.get_mesh("Cube")
Sphere.position.xyz = 0, 0, -10
scene= rc.Scene(meshes=[Sphere])
#window.event
def on_draw():
with rc.default_shader:
scene.draw()
#scene.clear()
#time.sleep(10)
pyglet.app.run()
Traceback (most recent call last):
File "C:\Users\Jeffery\Desktop\Art\Pyglet Game Engine\scripts\Ratcave_OBJ_Loader_Test 2.py", line 15, in <module>
obj_reader = rc.WavefrontReader(obj_filename)
File "C:\Users\Jeffery\AppData\Local\Programs\Python\Python37-32\lib\site-packages\ratcave\wavefront.py", line 28, in __init__
self.bodies = read_wavefront(file_name)
File "C:\Users\Jeffery\AppData\Local\Programs\Python\Python37-32\lib\site-packages\wavefront_reader\reading.py", line 114, in read_wavefront
materials = read_mtlfile(path.join(path.dirname(fname_obj), fname_mtl))
File "C:\Users\Jeffery\AppData\Local\Programs\Python\Python37-32\lib\site-packages\wavefront_reader\reading.py", line 88, in read_mtlfile
material[prefix] = tuple(float(d) for d in split_data)
File "C:\Users\Jeffery\AppData\Local\Programs\Python\Python37-32\lib\site-packages\wavefront_reader\reading.py", line 88, in <genexpr>
material[prefix] = tuple(float(d) for d in split_data)
ValueError: could not convert string to float: 'textures'

Related

How to fix AttributeError: 'Image' object has no attribute 'seek'. Did you mean: 'seed'?

I am trying to create a pptx or powerpoint file using python-pptx and reading the image using python wand library but getting error like AttributeError: 'Image' object has no attribute 'seek'. Did you mean: 'seed'?
Note: All the files are in same folder starts with 'watermarked_'
from io import FileIO
import os
from wand.image import Image
from pptx.util import Inches
from pptx import Presentation
def create_slide()->FileIO:
# Creating presentation object
root = Presentation()
for file in os.listdir():
if file.startswith('watermarked_'):
# Creating slide layout
first_slide_layout = root.slide_layouts[1]
slide = root.slides.add_slide(first_slide_layout)
shapes = slide.shapes
#Adding title or heading to the slide
title_shape = shapes.title
title_shape.text = f" Created By python-pptx for Watermarking "
#Adding sub-title with border to the slide
body_shape = shapes.placeholders[1]
tf = body_shape.text_frame
tf.text = f"This is a watermarked image of {file}"
with Image(filename = file) as watermarked_image:
#Maintianing the aspect ratio of the image
width, height = watermarked_image.size
ratio = height/width
new_width = width / 2
new_height = int(new_width * ratio)
watermarked_image.resize(int(new_width), new_height)
# Add the watermarked image to the slide
slide.shapes.add_picture(watermarked_image ,Inches(1), Inches(3))
root.save("Output.pptx")
create_slide()
Traceback (most recent call last):
File "/Users/quantum/Desktop/image/project.py", line 60, in <module>
quantum#MacBook-Air image % python -u "/Users/quantum/Desktop/image/project.py"
Traceback (most recent call last):
File "/Users/quantum/Desktop/image/project.py", line 60, in <module>
create_slide()
File "/Users/quantum/Desktop/image/project.py", line 57, in create_slide
slide.shapes.add_picture(watermarked_image ,Inches(1), Inches(3))
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/pptx/shapes/shapetree.py", line 332, in add_picture
image_part, rId = self.part.get_or_add_image_part(image_file)
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/pptx/parts/slide.py", line 39, in get_or_add_image_part
image_part = self._package.get_or_add_image_part(image_file)
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/pptx/package.py", line 36, in get_or_add_image_part
return self._image_parts.get_or_add_image_part(image_file)
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/pptx/package.py", line 151, in get_or_add_image_part
image = Image.from_file(image_file)
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/pptx/parts/image.py", line 168, in from_file
if callable(getattr(image_file, "seek")):
AttributeError: 'Image' object has no attribute 'seek'. Did you mean: 'seed'?
Any frequent help will be much appreciated
A wand.image.Image object is not a valid argument for Shapes.add_picture(). The first argument to that call needs to be the str path to an image file or a file-like object containing an image.
I suppose that means you'll need to save the modified image as a JPG or PNG or whatever and then provide the filename. You could also save it to a BytesIO object and pass that to .add_picture() as that would count as a file-like object and not require using the filesystem.

'TypeError: 'NoneType' object is not iterable' during running of opencv/kivy/python code

Okay for last 2 weeks or so I have been teaching myself both opencv and kivy in order to create a UI/Camera System for Autonomous mission from MATE ROV. (I don't feel like explaining about MATE ROV just google it) I have succeeded in creating both the UI and the camera implementation. However, whenever I go to add the cv2.HoughLinesP calculation to find the length of a rectangle in my test image.
[Test Image][1]
I get created by the code running for a short amount of time (usually runs through entire code a couple of times) then I get this.
Traceback (most recent call last):
File "main.py", line 87, in <module>
CamApp().run()
File "/home/mlees/kivy_venv/lib/python3.6/site-packages/kivy/app.py", line 855, in run
runTouchApp()
File "/home/mlees/kivy_venv/lib/python3.6/site-packages/kivy/base.py", line 504, in runTouchApp
EventLoop.window.mainloop()
File "/home/mlees/kivy_venv/lib/python3.6/site-packages/kivy/core/window/window_sdl2.py", line 747, in mainloop
self._mainloop()
File "/home/mlees/kivy_venv/lib/python3.6/site-packages/kivy/core/window/window_sdl2.py", line 479, in _mainloop
EventLoop.idle()
File "/home/mlees/kivy_venv/lib/python3.6/site-packages/kivy/base.py", line 339, in idle
Clock.tick()
File "/home/mlees/kivy_venv/lib/python3.6/site-packages/kivy/clock.py", line 591, in tick
self._process_events()
File "kivy/_clock.pyx", line 384, in kivy._clock.CyClockBase._process_events
File "kivy/_clock.pyx", line 414, in kivy._clock.CyClockBase._process_events
File "kivy/_clock.pyx", line 412, in kivy._clock.CyClockBase._process_events
File "kivy/_clock.pyx", line 167, in kivy._clock.ClockEvent.tick
File "main.py", line 56, in update
for line in buf8:
TypeError: 'NoneType' object is not iterable
I have no clue what is causing this error so if anyone can help me out that would be great. Full Code is below.
from kivy.uix.widget import Widget
from kivy.uix.gridlayout import GridLayout
from kivy.uix.image import Image
from kivy.uix.label import Label
from kivy.clock import Clock
from kivy.graphics.texture import Texture
import cv2
import numpy as np
class CamApp(App):
def build(self):
self.img0 = Image()
self.img1 = Image()
self.img2 = Image()
self.img3 = Image()
layout = GridLayout(cols = 4, rows = 3)
layout.add_widget(self.img0)
layout.add_widget(self.img1)
layout.add_widget(Label(text="HELP"))
layout.add_widget(Label(text="HELP"))
layout.add_widget(self.img2)
layout.add_widget(self.img3)
layout.add_widget(Label(text="HELP"))
layout.add_widget(Label(text="HELP"))
layout.add_widget(Label(text="HELP"))
layout.add_widget(Label(text="HELP"))
layout.add_widget(Label(text="HELP"))
layout.add_widget(Label(text="HELP"))
#opencv2 stuffs
self.capture = cv2.VideoCapture(0)
Clock.schedule_interval(self.update, 1.0/33.0)
return layout
def update(self, dt):
# display image from cam in opencv window
ret, frame = self.capture.read()
# Flip Image and set up first frame
buf1 = cv2.flip(frame, -1)
# Convert main frame to Grayscale
buf3 = cv2.cvtColor(buf1, cv2.COLOR_BGR2GRAY)
# Take Grayscale and add an adaptiveThreshold
buf5 = cv2.adaptiveThreshold(buf3,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY,11,2)
# Edge detection and line detection
buf7 = cv2.Canny(buf3,80,240,3)
buf8 = cv2.HoughLinesP(buf7, 1, np.pi/180, 60, np.array([]), 50, 5)
for line in buf8:
for x1, y1, x2, y2 in line:
cv2.line(buf8, (x1, y1), (x2, y2), (255, 255, 255), 4)
distance_pixels = np.sqrt(np.square(x2 - x1) + np.square(y2 - y1))
print(distance_pixels)
# Necessary to display all the transformations and other bullshit
buf0 = buf1.tostring()
buf2 = buf3.tostring()
buf4 = buf5.tostring()
buf6 = buf7.tostring()
# The next 9 lines are kivy bullshit to get the images on the screen.
texture0 = Texture.create(size=(frame.shape[1], frame.shape[0]), colorfmt='bgr')
texture1 = Texture.create(size=(frame.shape[1], frame.shape[0]), colorfmt='luminance')
texture2 = Texture.create(size=(frame.shape[1], frame.shape[0]), colorfmt='luminance')
texture3 = Texture.create(size=(frame.shape[1], frame.shape[0]), colorfmt='luminance')
texture0.blit_buffer(buf0, colorfmt='bgr', bufferfmt='ubyte')
texture1.blit_buffer(buf2, colorfmt='luminance', bufferfmt='ubyte')
texture2.blit_buffer(buf4, colorfmt='luminance', bufferfmt='ubyte')
texture3.blit_buffer(buf6, colorfmt='luminance', bufferfmt='ubyte')
# display image from the texture
self.img0.texture = texture0
self.img1.texture = texture1
self.img2.texture = texture2
self.img3.texture = texture3
# Here's the running shit.
if __name__ == '__main__':
CamApp().run()
cv2.destroyAllWindows()
Thanks in advance!
This error is arising because in some case, no line is found by HoughLinesP() function thus "buf8" have value "None" at those instances.
Add a line before starting the for loop to check if "buf8" is "None" or not. If not None process, else break the process.

PIL.UnidentifiedImageError: cannot identify image file

I'm working on GCP cloud functions and intend to write a functions which combines two images. But I', getting the following error when I invoke the function:
Traceback (most recent call last): File
"/env/local/lib/python3.7/site-packages/google/cloud/functions/worker.py",
line 346, in run_http_function result =
_function_handler.invoke_user_function(flask.request) File "/env/local/lib/python3.7/site-packages/google/cloud/functions/worker.py",
line 217, in invoke_user_function return
call_user_function(request_or_event) File
"/env/local/lib/python3.7/site-packages/google/cloud/functions/worker.py",
line 210, in call_user_function return
self._user_function(request_or_event) File "/user_code/main.py", line
74, in execute newIntro= generateIntroImage(nameMappings['stdName'],
nameMappings['stdPicture'], nameMappings['logo'],
nameMappings['stdYear'], nameMappings['font']) File
"/user_code/main.py", line 12, in generateIntroImage
images.append(Image.open(logo)) File
"/env/local/lib/python3.7/site-packages/PIL/Image.py", line 2862, in
open "cannot identify image file %r" % (filename if filename else fp)
PIL.UnidentifiedImageError: cannot identify image file '/tmp/logo.jpg'
I have ran this function on my local machine and it works as expected but when I deploy it on GCP, it gives this error and crashes. Here's my function:
from PIL import Image
from PIL import ImageFont
from PIL import ImageDraw
def generateIntroImage(stdName, stdPicture, logo, year, typeFace):
images = [Image.open(x) for x in [stdPicture, logo]]
widths, heights = zip(*(i.size for i in images))
total_width = sum(widths)
max_height = max(heights)
new_im = Image.new('RGB', (total_width, max_height))
x_offset = 0
for im in images:
new_im.paste(im, (x_offset,0))
x_offset += im.size[0]
font= ImageFont.truetype(typeFace, 70)
draw= ImageDraw.Draw(new_im)
draw.text((0, 0), stdName+"'s " +year+" Year Book", (0,0,0),font= font)
fileName= "/tmp/test.jpg"
new_im.save(fileName)
return fileName
These images are .jpg and .png files. Any idea what could be wrong?
Happened to me on Google Colab as well, apparently updating PIL version fixed the problem for me.
PIL throws error because it cannot identify the image format. Most probably the reason is that the image is corrupted and hence cannot be read (or "identified") by pillow's Image.open(). For example if you try opening the image in an IPython prompt, it would fail as well.
In [2]: from PIL import Image
In [3]: Image.open("176678612.jpg")
---------------------------------------------------------------------------
UnidentifiedImageError Traceback (most recent call last)
<ipython-input-3-3f91b2f4e49a> in <module>
----> 1 Image.open("176678612.jpg")
/opt/conda/envs/swin/lib/python3.7/site-packages/PIL/Image.py in open(fp, mode, formats)
3022 warnings.warn(message)
3023 raise UnidentifiedImageError(
-> 3024 "cannot identify image file %r" % (filename if filename else fp)
3025 )
3026
UnidentifiedImageError: cannot identify image file '176678612.jpg'
And the relevant piece of code handling this check is from PIL.Image.open()
"""
exception PIL.UnidentifiedImageError: If the image cannot be opened and
identified.
"""
raise UnidentifiedImageError(
"cannot identify image file %r" % (filename if filename else fp)
So, the fix is to delete the image, or replace it with an uncorrupted version.
you need to provide a downloadable link to the image. What worked for me was click on the download image and the copy that URL.

Resize image in Tkinter

So, I need to resize an image in tkinter. Before you do anything - this is not a duplicate. I have gone through every other question on this site and none have helped me. The thing with me is - I don't wan't to save the image. I need to load the image, resize it, then display it with PhotoImage in a label. I tried to use ImageTk, but for some reason it won't work.
Here's my code with ImageTk:
from tkinter import *
import PIL
from PIL import Image, ImageTk
root = Tk()
left_nose_path_white = Image.open(r'C:\Users\User\Documents\Python stuff\Other apps\Veteris\Dog photos\Advanced\Sides\GIF\Nose\Nose (left) - White.gif')
def resize_image():
global left_nose_path_white
total_screen_width = root.winfo_screenwidth()
total_screen_height = root.winfo_screenheight()
frame_width, frame_height = left_nose_path_white.size
dog_new_width = int(frame_width / 3)
dog_new_height = int(frame_height / 3)
left_nose_path_white = left_nose_path_white.resize((dog_new_width, dog_new_height), Image.LANCZOS)
resize_image()
left_nose_img_white = ImageTk.PhotoImage(file = left_nose_path_white)
label = Label(image = left_nose_img_white)
label.pack()
root.mainloop()
This returns the error:
File "C:\Users\User\AppData\Local\Programs\Python\Python37\lib\site-packages\PIL\ImageTk.py", line 124, in __del__
name = self.__photo.name
AttributeError: 'PhotoImage' object has no attribute '_PhotoImage__photo'
My code should find the width and height of the original image, divide it by 3, and then show it. The reason I don't want to have to save the image is because the user will open the application several times.
I'm new to using PILL/Pillow, so the answer may be obvious.
I have Pillow installed using pip.
I only have one version of Python on my computer (Python 3.7)
Full Error:
Traceback (most recent call last):
File "C:\Users\User\Documents\Python stuff\Other apps\Veteris\Scripts\Veteris_program.py", line 230, in <module>
left_nose_img_white = ImageTk.PhotoImage(file = left_nose_path_white)
File "C:\Users\User\AppData\Local\Programs\Python\Python37\lib\site-packages\PIL\ImageTk.py", line 95, in __init__
image = _get_image_from_kw(kw)
File "C:\Users\User\AppData\Local\Programs\Python\Python37\lib\site-packages\PIL\ImageTk.py", line 64, in _get_image_from_kw
return Image.open(source)
File "C:\Users\User\AppData\Local\Programs\Python\Python37\lib\site-packages\PIL\Image.py", line 2779, in open
prefix = fp.read(16)
AttributeError: 'Image' object has no attribute 'read'
Exception ignored in: <function PhotoImage.__del__ at 0x000002B0A8A49950>
Traceback (most recent call last):
File "C:\Users\User\AppData\Local\Programs\Python\Python37\lib\site-packages\PIL\ImageTk.py", line 124, in __del__
name = self.__photo.name
AttributeError: 'PhotoImage' object has no attribute '_PhotoImage__photo'
Thanks for the help!

Need help saving in PyMuPDF

This is a basic script that should insert a watermark image on the first page of a PDF and save it under a new name.
I could do the same with the same files in pdfrw, but I'm stuck with PyMuPDF (which I would prefer to use...).
The py file is in the same folder with the pdf and the png.
import fitz
input_file = "sample.pdf"
output_file = "sample_stamped.pdf"
stamp = "watermark.png"
doc = fitz.open(input_file)
rect = fitz.Rect(0, 0, 100, 100)
pix = fitz.Pixmap(stamp)
page = doc[0]
page.insertImage(rect, pixmap = pix, overlay = True)
doc.save(output_file)
I'm getting this error msg:
Traceback (most recent call last):
File "D:/Google Drive/Python/PDF/pdfstamp.py", line 14, in <module>
doc.save(output_file)
File "D:\Python\lib\site-packages\fitz\fitz.py", line 2411, in save
return _fitz.Document_save(self, filename, garbage, clean, deflate, incremental, ascii, expand, linear, pretty, decrypt)
RuntimeError: not a dict (array)
Thanks in advance for any help.

Resources