I am having a problem with numpy and openCV - python

ok so i tried this
import cv2 as cv
cvNet = cv.dnn.readNetFromTensorflow('frozen_inference_graph.pb', 'graph.pbtxt')
img = cv.imread('example.jpg')
rows = img.shape[0]
cols = img.shape[1]
cvNet.setInput(cv.dnn.blobFromImage(img, size=(300, 300), swapRB=True, crop=False))
cvOut = cvNet.forward()
for detection in cvOut[0,0,:,:]:
score = float(detection[2])
if score > 0.3:
left = detection[3] * cols
top = detection[4] * rows
right = detection[5] * cols
bottom = detection[6] * rows
cv.rectangle(img, (int(left), int(top)), (int(right), int(bottom)), (23, 230, 210), thickness=2)
cv.imshow('img', img)
cv.waitKey()
and it request me error like this
Traceback (most recent call last):
File "C:\WINDOWS\System32\numpy_init_.py", line 140, in
from . import _distributor_init
File "C:\WINDOWS\System32\numpy_distributor_init.py", line 34, in
from . import mklinit
ImportError: cannot import name 'mklinit' from partially initialized module 'numpy' (most likely due to a circular import) (C:\WINDOWS\System32\numpy_init.py)
Traceback (most recent call last):
File "C:\Users\phat\Downloads\start.py", line 1, in
import cv2 as cv
File "C:\Users\phat\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\cv2_init.py", line 5, in
from .cv2 import *
ImportError: numpy.core.multiarray failed to import
can anyone help me?

Related

Problems with Weasyprint: ModuleNotFoundError

I would like to display the text from an image and then have the coordinates determined for each word in the text. For this I use the following code:
from doctr.io import DocumentFile
from doctr.models import ocr_predictor
import json
import math
import PIL
from PIL import ImageDraw
import matplotlib.pyplot as plt
model = ocr_predictor (det_arch='db_resnet50', reco_arch='crnn_vgg16_bn',pretrained=True)
bildpfad = "C:/Users/b2/Documents/Analysetext_1.png"
bild = DocumentFile.from_images (bildpfad)
ergebnis = model (bild)
output = ergebnis.export ()
with open ("C:/Users/b2/Documents/docTR_OCR_output.json", "w") as f:
f.write (json.dumps (output, indent=1))
f.close ()
ergebnis.show (bild)
# Geometrische Koordinaten
for object_1 in output ['pages'] [0] ["blocks"]:
for object_2 in object_1 ["lines"]:
for object_3 in object_2 ["words"]:
print ("{}: {}".format (object_3 ["geometry"], object_3 ["value"]))
# Output like [x_min, x_max, y_min, y_max]
# Geographische Koordinaten
def convert_coordinates (geometry, page_dim):
len_x = page_dim[1]
len_y = page_dim[0]
(x_min, y_min) = geometry[0]
(x_max, y_max) = geometry[1]
x_min = math.floor(x_min * len_x)
x_max = math.ceil(x_max * len_x)
y_min = math.floor(y_min * len_y)
y_max = math.ceil(y_max * len_y)
return [x_min, x_max, y_min, y_max]
def get_coordinates (output):
page_dim = output ['pages'][0]["dimensions"]
text_coordinates = []
for object_1 in output ['pages'][0]["blocks"]:
for object_2 in object_1 ["lines"]:
for object_3 in object_2 ["words"]:
converted_coordinates = convert_coordinates (object_3 ["geometry"], page_dim)
print ("{}: {}".format (converted_coordinates, object_3 ["values"]))
text_coordinates.append (converted_coordinates)
return text_coordinates
graphical_coordinates = get_coordinates (output)
print (graphical_coordinates)
# Plot graphische Koordinaten
def draw_bounds(bild, bound):
draw = ImageDraw.Draw(bild)
for b in bound:
p0, p1, p2, p3 = [b[0],b[2]], [b[1],b[2]], \
[b[1],b[3]], [b[0],b[3]]
draw.line([*p0,*p1,*p2,*p3,*p0], fill='blue', width=2)
return bild
bild = PIL.Image.open(bildpfad)
result_image = draw_bounds(bild, graphical_coordinates)
plt.figure(figsize=(15,15))
plt.imshow(result_image)
At the beginning I had the following error:
OSError: cannot load library 'gobject-2.0-0': error 0x7e. Additionally, ctypes.util.find_library() did not manage to locate a library called 'gobject-2.0-0'
I was then able to fix this error and now the following is displayed:
ModuleNotFoundError: No module named 'weasyprint.text.ffi'; 'weasyprint.text' is not a package
The whole output is:
Traceback (most recent call last):
File "c:/Users/b2/Documents/Übungen/Distanzberechnungen/Textdetection_Übung_3.py", line 3, in <module>
from doctr.io import DocumentFile
File "C:\Users\b2\anaconda3\envs\Python_3_6\lib\site-packages\doctr\__init__.py", line 1, in <module>
from . import datasets, io, models, transforms, utils
File "C:\Users\b2\anaconda3\envs\Python_3_6\lib\site-packages\doctr\datasets\__init__.py", line 3, in <module>
from .generator import *
File "C:\Users\b2\anaconda3\envs\Python_3_6\lib\site-packages\doctr\datasets\generator\__init__.py", line 4, in <module>
from .tensorflow import *
File "C:\Users\b2\anaconda3\envs\Python_3_6\lib\site-packages\doctr\datasets\generator\tensorflow.py", line 8, in <module>
from .base import _CharacterGenerator, _WordGenerator
File "C:\Users\b2\anaconda3\envs\Python_3_6\lib\site-packages\doctr\datasets\generator\base.py", line 11, in <module>
from doctr.io.image import tensor_from_pil
File "C:\Users\b2\anaconda3\envs\Python_3_6\lib\site-packages\doctr\io\__init__.py", line 2, in <module>
from .html import *
File "C:\Users\b2\anaconda3\envs\Python_3_6\lib\site-packages\doctr\io\html.py", line 8, in <module>
from weasyprint import HTML
File "C:\Users\b2\anaconda3\envs\Python_3_6\lib\site-packages\weasyprint\__init__.py", line 315, in <module>
from .css import preprocess_stylesheet # noqa isort:skip
File "C:\Users\b2\anaconda3\envs\Python_3_6\lib\site-packages\weasyprint\css\__init__.py", line 25, in <module>
from . import computed_values, counters, media_queries
File "C:\Users\b2\anaconda3\envs\Python_3_6\lib\site-packages\weasyprint\css\computed_values.py", line 9, in <module>
from ..text.ffi import ffi, pango, units_to_double
ModuleNotFoundError: No module named 'weasyprint.text.ffi'; 'weasyprint.text' is not a package
I hope you can help me to fix this error. Thank you in advance

Mediapipe image pose estimation ERROR: No subgraph in the model CalculatorGraph::Run() failed in Run

I do like to estimate the pose from an image using MediaPipe, Following their Tutorial I'm getting this error:
ERROR: No subgraph in the model
CalculatorGraph::Run() failed in Run
while doing that!
This error appears in Ubuntu 20.04, boost 1.71, mediapipe 0.8.10.1
The same code is working perfectly on Windows.
Can you please tell me how can I resolve this error? thanks in advance.
The code I'm using to draw the pose:
import cv2
import mediapipe as mp
import numpy as np
mp_drawing = mp.solutions.drawing_utils
mp_drawing_styles = mp.solutions.drawing_styles
mp_pose = mp.solutions.pose
def draw_pose(image):
"""
"""
BG_COLOR = (192, 192, 192)
with mp_pose.Pose(
static_image_mode=True,
model_complexity=2,
enable_segmentation=True,
min_detection_confidence=0.5) as pose:
image_height, image_width, _ = image.shape
# Convert the BGR image to RGB before processing.
results = pose.process(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))
if not results.pose_landmarks:
return image
annotated_image = image.copy()
# Draw segmentation on the image.
# To improve segmentation around boundaries, consider applying a joint
# bilateral filter to "results.segmentation_mask" with "image".
condition = np.stack((results.segmentation_mask,) * 3, axis=-1) > 0.1
bg_image = np.zeros(image.shape, dtype=np.uint8)
bg_image[:] = BG_COLOR
annotated_image = np.where(condition, annotated_image, bg_image)
# Draw pose landmarks on the image.
mp_drawing.draw_landmarks(
annotated_image,
results.pose_landmarks,
mp_pose.POSE_CONNECTIONS,
landmark_drawing_spec=mp_drawing_styles.get_default_pose_landmarks_style())
return annotated_image
path = "/media/user/WD/Vision_Module/"
imName = "frame.png"
img = cv2.imread(path+imName)
res = draw_pose(img)
cv2.imshow(res)
cv2.waitKey(0)
Error Log:
INFO: Created TensorFlow Lite XNNPACK delegate for CPU.
ERROR: No subgraph in the model.
WARNING: Logging before InitGoogleLogging() is written to STDERR
E20220111 09:38:55.000392 9542 calculator_graph.cc:805] INTERNAL: CalculatorGraph::Run() failed in Run:
Calculator::Open() for node "poselandmarkbyroicpu__inferencecalculator__poselandmarkbyroicpu__InferenceCalculator" failed: ; interpreter_ilure (mediapipe/calculators/tensor/inference_calculator_cpu.cc:152)
Traceback (most recent call last):
File "/media/user/WD/Vision_Module/pose_est.py", line 24, in draw_pose
results = pose.process(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))
File "/home/user/.local/lib/python3.8/site-packages/mediapipe/python/solutions/pose.py", line 185, in process
results = super().process(input_data={'image': image})
File "/home/user/.local/lib/python3.8/site-packages/mediapipe/python/solution_base.py", line 334, in process
self._graph.wait_until_idle()
RuntimeError: CalculatorGraph::Run() failed in Run:
Calculator::Open() for node "poselandmarkbyroicpu__inferencecalculator__poselandmarkbyroicpu__InferenceCalculator" failed: ; interpreter_ilure (mediapipe/calculators/tensor/inference_calculator_cpu.cc:152)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/media/user/WD/Vision_Module/pose_est.py", line 49, in <module>
res = draw_pose(img)
File "/media/user/WD/Vision_Module/pose_est.py", line 38, in draw_pose
mp_drawing.draw_landmarks(
File "/home/user/.local/lib/python3.8/site-packages/mediapipe/python/solution_base.py", line 546, in __exit__
self.close()
File "/home/user/.local/lib/python3.8/site-packages/mediapipe/python/solution_base.py", line 352, in close
self._graph.close()
RuntimeError: CalculatorGraph::Run() failed in Run:
Calculator::Open() for node "poselandmarkbyroicpu__inferencecalculator__poselandmarkbyroicpu__InferenceCalculator" failed: ; interpreter_ilure (mediapipe/calculators/tensor/inference_calculator_cpu.cc:152)
model_complexity=0;
your code will run perfectly

Can't import using * with

I have the following code:
https://github.com/marcomusy/vedo/blob/master/examples/basic/colorlines.py
"""Color lines by a scalar"""
from vedo import *
pts1 = [(sin(x/8), cos(x/8), x/5) for x in range(25)]
l1 = Line(pts1).c('black')
l2 = l1.clone().rotateZ(180).shift(1,0,0)
dist = mag(l1.points()-l2.points()) # make up some scalar values
# The trick here is to think that the "body" of a line is a cell
# so we can color cells as we do for any other polygonal mesh:
lines = Lines(l1, l2).lw(4).cmap('Accent', dist, on='cells')
lines.addScalarBar(title='distance') # or e.g.:
# lines.addScalarBar3D(title='distance').scalarbar.rotateX(90).pos(1,1,2)
show(l1,l2, lines, __doc__, axes=1, bg2='lightblue', viewup='z')
However, this gives me the following error:
Traceback (most recent call last):
File "vedo.py", line 2, in <module>
from vedo import *
File "/Users/prikshetsharma/Documents/clotorch/src/clotorch/flight/vedo.py", line 4, in <module>
pts1 = [(sin(x/8), cos(x/8), x/5) for x in range(25)]
File "/Users/prikshetsharma/Documents/clotorch/src/clotorch/flight/vedo.py", line 4, in <listcomp>
pts1 = [(sin(x/8), cos(x/8), x/5) for x in range(25)]
NameError: name 'sin' is not defined
However, sin is imported from numpy in the init.py file of vedo, so it should be defined in this file.

How to fix Memory Error while using PIL in Python

I'm creating a bot to automate the label making process. i encountered this problem while trying to save (append) multiple images to a pdf. This issue only happens when I'm using a large no. of images and the program works fine if I'm using a few image.
I want to fix this program so that it can process unlimited no. of images and append it to a single pdf file.
from PIL import Image, ImageDraw, ImageFont
import textwrap
import pandas
import datetime
import numpy
import os
from tkinter import filedialog
from tqdm import tqdm_gui
datenow = datetime.datetime.now()
pdate = datenow.strftime("%d-%m-%y")
y = 0
excel = filedialog.askopenfilename(initialdir="/", title="Select A File", filetypes=(("Excel File", "*.xlsx"),("all files", "*.*")))
save_dir = filedialog.askdirectory()
imlist = []
df = pandas.read_excel(excel)
for data in (df.values):
name, no = data
x = 0
while x<no:
x = x+1
y = y+1
LH = len(name)
if LH < 32:
W = 70
Lng = 16
if LH > 32:
W = 53
Lng = 22
name = name.upper()
para = textwrap.wrap(name, width=Lng)
MAX_W, MAX_H = 800, 592
im = Image.open('TFC.jpg')
draw = ImageDraw.Draw(im)
font = ImageFont.truetype('OpenSans-ExtraBold.ttf', W)
current_h, pad = 155, -5
for line in para:
w, h = draw.textsize(line, font=font)
draw.text(((MAX_W - w) / 2, current_h), line, font=font)
current_h += h + pad
imlist.append(im)
im.save(f'{save_dir}/{pdate}{" TF "}{y}.pdf' , save_all=True, append_images=imlist)
os.startfile(save_dir)
The error which I'm getting:
"C:\Users\RAJA MONSINGH\PycharmProjects\Fuzzy\venv\Scripts\python.exe" "C:/Users/RAJA MONSINGH/PycharmProjects/Lable/lable3.py"
Traceback (most recent call last):
File "C:\Users\RAJA MONSINGH\AppData\Roaming\Python\Python38\site-packages\PIL\ImageDraw.py", line 465, in Draw
return im.getdraw(mode)
AttributeError: 'JpegImageFile' object has no attribute 'getdraw'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:/Users/RAJA MONSINGH/PycharmProjects/Lable/lable3.py", line 34, in <module>
draw = ImageDraw.Draw(im)
File "C:\Users\RAJA MONSINGH\AppData\Roaming\Python\Python38\site-packages\PIL\ImageDraw.py", line 467, in Draw
return ImageDraw(im, mode)
File "C:\Users\RAJA MONSINGH\AppData\Roaming\Python\Python38\site-packages\PIL\ImageDraw.py", line 59, in __init__
im.load()
File "C:\Users\RAJA MONSINGH\AppData\Roaming\Python\Python38\site-packages\PIL\ImageFile.py", line 233, in load
s = read(self.decodermaxblock)
File "C:\Users\RAJA MONSINGH\AppData\Roaming\Python\Python38\site-packages\PIL\JpegImagePlugin.py", line 394, in load_read
s = self.fp.read(read_bytes)
MemoryError
Process finished with exit code 1
Files needed to run the program:
https://drive.google.com/file/d/1rS-auW0MHmdjoPlNET71isL8AyEPPyGT/view?usp=sharing

Why is Image.composite returning a "bad mask" error when I used one of the 2 images as a mask?

I followed this tutorial and the guy used the one of the 2 images as the mask. But for me it's not working. Why is this?
from PIL import Image
img1 = Image.open("beach.jpg")
img2 = Image.open("joker.jpg")
maxsize = min(img1.size,img2.size)
newratio = min(maxsize[0]/img2.size[0],maxsize[1]/img1.size[1])
newimg1width = int(img1.size[0]*newratio)
newimg1height = int(img1.size[1]*newratio)
newimgtuple = (newimg1width,newimg1height)
newimg = img1.resize(newimgtuple)
compimg = Image.composite(newimg, img2, newimg)
compimg.save("compimg.jpg")
The error:
Traceback (most recent call last):
File "C:\Users\dude\Desktop\Desktop\Projects\Youtube\Wordtoon\test.py", line 44, in <module>
compimg = Image.composite(newimg, img2, newimg)
File "C:\Users\dude\AppData\Local\Programs\Python\Python35-32\lib\site-packages\PIL\Image.py", line 2376, in composite
image.paste(image1, None, mask)
File "C:\Users\dude\AppData\Local\Programs\Python\Python35-32\lib\site-packages\PIL\Image.py", line 1344, in paste
self.im.paste(im, box, mask.im)
ValueError: bad transparency mask

Categories

Resources