3

I use python cv2(window10, python3.6) to write text in the image, when the text is English it works, but when I use Arabic text it writes messy code in the image.

Below is my code:

import cv2 
import numpy as np
blank_image = np.zeros((100,300,3), np.uint8)
font = cv2.FONT_HERSHEY_SIMPLEX 
org = (10, 50) 
fontScale = .5
color = (255, 0, 0)  
thickness = 1
blank_image = cv2.putText(blank_image, "اللغة العربية", org, font,  
                   fontScale, color, thickness, cv2.LINE_AA)
window_name = 'Image'
cv2.imshow(window_name, blank_image) 
cv2.waitKey(0)
cv2.destroyAllWindows()

the problem here blank_image = cv2.putText(blank_image, "اللغة العربية", org, font,
fontScale, color, thickness, cv2.LINE_AA)

Output

OMRAN
  • 41
  • 3
  • 1
    Different script, same problem: https://stackoverflow.com/questions/50854235 – HansHirse Jan 24 '20 at 13:48
  • I try it and the output not work .. maybe because of different language – OMRAN Jan 24 '20 at 14:57
  • That module was likely only written to support English, and/or certain character codes. It probably uses the lower portion of the ASCII character set, not the whole extended set of unicode characters that were added over time. You'll need to find a module that was written to support the characters/languages you are interested in, or, if you have access to the source, perhaps you can modify it to extend the character set it knows about, or write your own module, or train some module on new data that fits your needs. Also check your character encoding. – SherylHohman Jan 24 '20 at 20:29
  • Does this answer your question? [How to draw Chinese text on the image using \`cv2.putText\`correctly? (Python+OpenCV)](https://stackoverflow.com/questions/50854235/how-to-draw-chinese-text-on-the-image-using-cv2-puttextcorrectly-pythonopen) – SherylHohman Jan 24 '20 at 20:29

1 Answers1

7
fontpath = "arial.ttf" # <== download font
font = ImageFont.truetype(fontpath, 32)
img_pil = Image.fromarray(frame)
draw = ImageDraw.Draw(img_pil)
draw.text((50, 80),'عربي', font = font)
img = np.array(img_pil)
cv2.imshow(window_name, img) 
import cv2 
import arabic_reshaper
from bidi.algorithm import get_display
import numpy as np
from PIL import ImageFont, ImageDraw, Image


cap = cv2.VideoCapture(0)

while(True):
    # Capture frame-by-frame
    ret, frame = cap.read()
    text = "ذهب الطالب الى المدرسة"
    reshaped_text = arabic_reshaper.reshape(text)
    bidi_text = get_display(reshaped_text) 
    fontpath = "arial.ttf" # <== https://www.freefontspro.com/14454/arial.ttf  
    font = ImageFont.truetype(fontpath, 32)
    img_pil = Image.fromarray(frame)
    draw = ImageDraw.Draw(img_pil)
    draw.text((50, 80),bidi_text, font = font)
    img = np.array(img_pil)

    cv2.imshow('window_name', img) 


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

# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()