Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error 'module' object has no attribute 'freetype'

I am using this code Link but it displays error of module object has no attribute i tried to pip install freetype but nothing happened. Can anyone please guide me with this.

import cv2
import numpy as np   
img = np.zeros((100, 300, 3), dtype=np.uint8)

ft = cv2.freetype.createFreeType2()
ft.loadFontData(fontFileName='Ubuntu-R.ttf',
                id=0)
ft.putText(img=img,
           text='Quick Fox',
           org=(15, 70),
           fontHeight=60,
           color=(255,  255, 255),
           thickness=-1,
           line_type=cv2.LINE_AA,
           bottomLeftOrigin=True)

cv2.imwrite('image.png', img)
like image 851
Munazza Ali Avatar asked Dec 09 '17 08:12

Munazza Ali


3 Answers

If cv2.freetype does not run in python you can still use freetype-py module.

I have written a wrapper around the PIL library api calls in opencv for python2/3 which can be used in the following way: (download from https://github.com/bunkahle/PILasOPENCV )

from __future__ import print_function
import PILasOPENCV as Image
import PILasOPENCV as ImageDraw
import PILasOPENCV as ImageFont
import cv2

font = ImageFont.truetype("arial.ttf", 30)
print(font)
im = Image.new("RGB", (512, 512), "grey")
draw = ImageDraw.Draw(im)
text = "Some text in arial"
draw.text((100, 250), text, font=font, fill=(0, 0, 0))
print(ImageFont.getsize(text, font))
mask = ImageFont.getmask(text, font)
print(type(mask))
cv2.imshow("mask", mask)
im.show()
im_numpy = im.getim()
print(type(im_numpy), im_numpy.shape, im_numpy.dtype)

It uses the freetype-py module in the background. PILasOPENCV is actually a project for migrating old PIL projects to OPENCV. Install with

setup.py install 

or

pip install PILasOPENCV 

More details and test can be found in github.

like image 181
bunkus Avatar answered Nov 11 '22 05:11

bunkus


I find opencv-contrib-python-4.5.3.56 does not have freetype. I downgraded it to version 4.4.0.46, then it works.

pip3 install opencv-contrib-python==4.4.0.46
like image 35
luckiday Avatar answered Nov 11 '22 05:11

luckiday


You're just missing opencv-contrib, you can install that with pip install opencv-contrib-python.

like image 1
fireant Avatar answered Nov 11 '22 05:11

fireant