How to draw arabic text on the image using `cv2.putText`correctly? (Python+OpenCV) - python-3.x

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)

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()

#before opening the programme
#first download arabic_reshaper lib write in Anaconda prompt
#"pip install arabic_reshaper"
#and download bidi lib write in Anaconda prompt
#"pip install python-bidi"
import arabic_reshaper
from bidi.algorithm import get_display
import numpy as np
from PIL import ImageFont, ImageDraw, Image
import cv2
img =cv2.imread("sun.jpg")
fontpath = "arial.ttf" # <== download font
font = ImageFont.truetype(fontpath, 32)
img_pil = Image.fromarray(img)
draw = ImageDraw.Draw(img_pil)
text="اللغة العربية"
reshaped_text = arabic_reshaper.reshape(text)
bidi_text = get_display(reshaped_text)
draw = ImageDraw.Draw(img_pil)
draw.text((50, 80),bidi_text, font = font)
img = np.array(img_pil)
cv2.imshow("image with arabic", img)
cv2.waitKey(0)
cv2.destroyAllWindows()

Related

Python - image watermark

my goal is to create a watermark image, based on a logo (TIF format) and a background image (JPG).
I'm using this code:
from PIL import Image
def watermark_with_transparency(input_image_path,
output_image_path,
watermark_image_path,
position):
base_image = Image.open(input_image_path)
watermark = Image.open(watermark_image_path)
width, height = base_image.size
transparent = Image.new('RGBA', (width, height), (0,0,0,0))
transparent.paste(base_image, (0,0))
transparent.paste(watermark, position, mask=watermark)
transparent.show()
transparent.save(output_image_path)
Watermark image is a trasparent TIF.
If I run above code, watermark result does not include any logo.
What I'm doing wrong?
from PIL import Image,ImageDraw, ImageFont
path=r'/home/anuj/FIle_server/production/AI_PROJECT/SEQ_001/sq1/frm_seq_v001.001.jpeg' #This is path of your image
demo_image = Image.open(path)
img_width, img_height =demo_image.size
draw_image = ImageDraw.Draw(demo_image)
text_image ="HQVFX" #Here you can assign your watermark.
font_image =ImageFont.truetype('/home/anuj/FIle_server/task/WaterBrush-Regular.ttf',50)
text_width, text_height = draw_image.textsize(text_image,font_image)
font_margin = 10
x = img_width - text_width - font_margin
y = img_height - text_height - font_margin
draw_image.text((x,y), text_image, font= font_image)
demo_image.show()
demo_image.save("watermark.jpg")

How to remove shadows from a video that has static background?

I am trying to detect moving object and remove shadow from a video that has a static background. I am using Mixture of Gaussians(MOG) method to detect moving objects. I am using opencv3 and python 3.5. How can I remove shadows from the video and foreground mask both? I have used erosion and dilation for reducing noise. But it doesn't remove the shadows.
import cv2
import numpy as np
cap = cv2.VideoCapture('TownCentreXVID.avi')
fgbg = cv2.createBackgroundSubtractorMOG2()
while(1):
_, frame = cap.read()
mask = fgbg.apply(frame)
kernel = np.ones((5,5),np.uint8)
opening = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel)
closing = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel)
window = cv2.namedWindow('Original', cv2.WINDOW_NORMAL| cv2.WINDOW_KEEPRATIO )
window = cv2.namedWindow('Mask', cv2.WINDOW_NORMAL| cv2.WINDOW_KEEPRATIO)
window = cv2.namedWindow('Opening', cv2.WINDOW_NORMAL| cv2.WINDOW_KEEPRATIO )
#window = cv2.namedWindow('Closing', cv2.WINDOW_NORMAL| cv2.WINDOW_KEEPRATIO)
cv2.imshow('Original',frame)
cv2.imshow('Mask',thresh)
cv2.imshow('Opening',opening)
#cv2.imshow('Closing',closing)
k = cv2.waitKey(5) & 0xFF
if k == 27:
break
cv2.destroyAllWindows()
cap.release()
The backgroundsubtractor returns a mask where foreground object are white and shadows are gray.
You can use thresholding to create a new mask without shadow, or with only the shadow.
Use the mask without the shadows to get only the foreground.
Use the mask with only shadow to replace the shadow on the background (with a reference background image).
Result:
Code:
import cv2
import numpy as np
# load image / mask
mask = cv2.imread("mask.png",0)
#threshold mask
ret, foreground = cv2.threshold(mask, 200, 255, cv2.THRESH_BINARY)
ret, shadow = cv2.threshold(mask, 200, 255, cv2.THRESH_TOZERO_INV)
# stack images vertically
res = np.concatenate((mask,foreground,shadow),axis=0)
#show image
cv2.imshow("Result",res)
cv2.waitKey(0)
cv2.destroyAllWindows()

AttributeError: module 'cv2.cv2' has no attribute 'rectange'

I am using the following code on python 3.7
import cv2
import numpy as np
face_cascade = cv2.CascadeClassifier('D:\\ET\\haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier('D:\\ET\\haarcascade_eye.xml')
cap = cv2.VideoCapture(0)
while True:
ret, img = cap.read()
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
for (x,y,w,h) in faces:
cv2.rectange(img,(x,y),(x+w,y+h),(255,0,0),2)
roi_gray = gray[y:y+h, x:x+w]
roi_color = img[y:y+h, x:x+w]
eyes = eye_cascade.detectMultiScale(roi_gray)
for (ex,ey,ew,eh) in eyes:
cv2.rectangle(roi_color,(ex,ey), (ex+ew,ey+eh),(0,255,0),2)
cv2.imshow('img',img)
k = cv2.waitKey(30) & 0xFF
if k == 27:
break
cap.release()
cv2.destroyAllWindows()
the following is installed:
opencv-contrib-python-3.4.4.19
The error is telling you that cv2 doesn't have anything called rectange, but it does have something called rectangle. You misspelled it:
cv2.rectange(img,(x,y),(x+w,y+h),(255,0,0),2)

grabscreen.py Python win32api

Any Linux or Mac OS equivalent libraries to Win32gui, or to this code ?
working on an outside project and this windows code will help me grab the screen. Havent been able to find any libraries that are similar. Thank you
def grab_screen(region=None):
hwin = win32gui.GetDesktopWindow()
if region:
left,top,x2,y2 = region
width = x2 - left + 1
height = y2 - top + 1
else:
width = win32api.GetSystemMetrics(win32con.SM_CXVIRTUALSCREEN)
height = win32api.GetSystemMetrics(win32con.SM_CYVIRTUALSCREEN)
left = win32api.GetSystemMetrics(win32con.SM_XVIRTUALSCREEN)
top = win32api.GetSystemMetrics(win32con.SM_YVIRTUALSCREEN)
hwindc = win32gui.GetWindowDC(hwin)
srcdc = win32ui.CreateDCFromHandle(hwindc)
memdc = srcdc.CreateCompatibleDC()
bmp = win32ui.CreateBitmap()
bmp.CreateCompatibleBitmap(srcdc, width, height)
memdc.SelectObject(bmp)
memdc.BitBlt((0, 0), (width, height), srcdc, (left, top), win32con.SRCCOPY)
signedIntsArray = bmp.GetBitmapBits(True)
img = np.fromstring(signedIntsArray, dtype='uint8')
img.shape = (height,width,4)
srcdc.DeleteDC()
memdc.DeleteDC()
win32gui.ReleaseDC(hwin, hwindc)
win32gui.DeleteObject(bmp.GetHandle())
return cv2.cvtColor(img, cv2.COLOR_BGRA2RGB)
You can grab the screen with pyautogui:
import pyautogui
image = pyautogui.screenshot('filename.png')
You can do this :)
I think Mac OS can't use those WiIn32gui libraries.
instead you can use pillow for grabbing screen.
Screen size can be changed depends on the size you want.
import cv2
import numpy as np
import pyautogui
from PIL import ImageGrab
screen_w = 1920
screen_h = 1080
while True:
rgb = ImageGrab.grab(bbox=(0, 0, screen_w, screen_h))
rgb = np.array(rgb)
cv2.imshow('window_frame', rgb)
if cv2.waitKey(1) & 0xFF == ord('q'):
break

PNG image that support scaling and changing transparency in python

I want to show PNG picture on canvas.
Before it I need to resize it and change transparency.
I found that I can load image and change alpha channel with PhotoImage like this:
image1 = PIL.Image.open('aqua.png')
image1.putalpha(128)
gif1 = ImageTk.PhotoImage(image1)
Also I can load PhotoImage and resize it like this:
gif1 = PhotoImage(file = 'aqua.png')
gif1 = gif1.subsample(5)
But I can't perform both this things on same PhotoImage
I understand that PhotoImage and ImageTk.PhotoImage are different classes in my code.
>> print (ImageTk.PhotoImage)
<class 'PIL.ImageTk.PhotoImage'>
>> print (PhotoImage)
<class 'tkinter.PhotoImage'>
I tried to found functionality that I need in both classes but without success.
Maybe I need perform subsample and than convert my tkinter.PhotoImage to PIL.ImageTk.PhotoImage and then perform putalpha but it sounds weird.
Please refer me to right direction about png cooking in Python.
Here is all my code:
from tkinter import *
import PIL
from PIL import Image, ImageTk
canvas = Canvas(width = 200, height = 200)
canvas.pack(expand = YES, fill = BOTH)
image1 = PIL.Image.open('aqua.png')
image1.putalpha(128)
gif1 = ImageTk.PhotoImage(image1)
# gif1 = PhotoImage(file = 'aqua.png')
# next line will not work in my case
gif1 = gif1.subsample(5)
canvas.create_image(0, 0, image = gif1, anchor = NW)
mainloop()
You can use the resize method included in the Image class. Here is the modified code:
from tkinter import *
from PIL import Image, ImageTk
canvas = Canvas(width = 200, height = 200)
canvas.pack(expand = YES, fill = BOTH)
image1 = Image.open('aqua.png')
image1.putalpha(128)
image1 = image1.resize((image1.width//5,image1.height//5))
gif1 = ImageTk.PhotoImage(image1)
canvas.create_image(0, 0, image = gif1, anchor = NW)
mainloop()

Resources