Watermark in the photo - python-3.x

I'm making a watermark in the photo. How to make a watermark for several photos at once? and How to save multiple photos at once? which loop should be and in which part of the code?
from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont
from PIL import ImageOps
def watermark_text(input_image_path,
output_image_path,
text, pos):
photo = Image.open(input_image_path)
drawing = ImageDraw.Draw(photo)
white = (3, 8, 12)
font = ImageFont.truetype("/Roboto-Regular.ttf", 150)
drawing.text(pos, text, fill=white, font=font)
photo.show()
photo.save(output_image_path)
if __name__ == '__main__':
img = 'new7093.JPG'
watermark_text(img, '11112.JPG',
text='sportves.ru',
pos=(300,500))

How about using multiprocessing.
from concurrent.futures import ProcessPoolExecutor
import os
img_list = os.listdir('path-to-image')
output_img_list = [i +'.output' for i in img_list]
text='sportves.ru'
pos=(300,500)
with ThreadPoolExecutor(max_workers=4) as executor:
futures = [executor.submit(watermark_text, input_image_path, output_image_path, text, pos)
for input_image_path, output_image_path
in zip(img_list, output_img_list)
]

It is should work). Replace a save path and append images to put watermarks.
from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont
def watermark_text(input_image_path,
output_image_path,
text, pos):
global new_images
photo = Image.open(input_image_path)
drawing = ImageDraw.Draw(photo)
white = (3, 8, 12)
font = ImageFont.truetype("/Roboto-Regular.ttf", 150)
drawing.text(pos, text, fill=white, font=font)
photo.show()
new_images.append(photo)
if __name__ == '__main__':
images = ['new7093.JPG', 'something.phg'] # list of photos without watermark
new_images = [] # list of photos with watermark
for img in images:
watermark_text(img, '11112.JPG',
text='sportves.ru',
pos=(300, 500))
new_images[0].save(r'C:\Users\You\Desktop', save_all=True,
append_images=new_images[1:]) # replace by you path

Related

How to split the image into 4 equal parts and do some processing on each part and then finally merge all the processed image parts?

import cv2;
import math;
import numpy as np;
import image_slicer;
import PIL;
from PIL import Image
import time
import concurrent.futures
import image_slicer
from image_slicer import join
def DCP(im,i):
pil_image = im
opencvImage = cv2.cvtColor(np.array(pil_image), cv2.COLOR_RGB2BGR)
src= opencvImage;
I = src.astype('float64')/255;
dark = DarkChannel(I,15);
A = AtmLight(I,dark);
te = TransmissionEstimate(I,A,15);
t = TransmissionRefine(src,te);
J = Recover(I,t,A,0.1);
cv2.imwrite("J"+str(i)+".jpg",J*255);
tiles = image_slicer.slice('o1.jpg', 4, save=False)
with concurrent.futures.ProcessPoolExecutor() as executor:
for tile in tiles:
results = [executor.submit(DCP,tile.image,i)]
i=i+1
i=1
for tile in tiles:
tile.image = Image.open("J"+str(i)+".jpg")
i=i+1
img = join(tiles)
img =img.convert("RGB")
img.save('Dehaze_Parallel.jpg')
finish = time.perf_counter()
print(f'Finished in{round(finish-start,2)} seconds')
The ultimate goal is to split the image into 4 parts, process them parallelly using the multiprocessing concept, and then merge the processed all the processed image parts into a single image.
Please refer my comments for more details.

How to extract text from image

I have tried most of the solutions on the site to extract data from the image,
only this script worked with the format *.tif, and gave me correct data
'''
from PIL import Image
import glob
import pytesseract
image_list = []
for filename in glob.glob(my_image):
im=Image.open(filename)
image_list.append(im)
pytesseract.pytesseract.tesseract_cmd="C:\\Program Files\\Tesseract-OCR\\tesseract.exe"
texts = [pytesseract.image_to_string(img,lang = 'eng') for img in image_list]
'''
However, this is not working with *.png and *.jpg, I tried the following:
'''
import cv2
import numpy as np
image = cv2.imread('1.jpg')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
sharpen_kernel = np.array([[-1,-1,-1], [-1,9,-1], [-1,-1,-1]])
sharpen = cv2.filter2D(gray, -1, sharpen_kernel)
thresh = cv2.threshold(sharpen, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3,3))
close = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel, iterations=1)
result = 255 - close
'''
And like,
'''
import os
from PIL import Image
import cv2
import pytesseract
import ftfy
import uuid
filename = img
image = cv2.imread(os.path.join(filename))
gray = cv2.threshold(image, 200, 255, cv2.THRESH_BINARY)[1]
gray = cv2.resize(gray, (0, 0), fx=3, fy=3)
gray = cv2.medianBlur(gray, 9)
filename = str(uuid.uuid4())+".jpg"
cv2.imwrite(os.path.join(filename), gray)
config = ("-l eng --oem 3 --psm 11")
text = pytesseract.image_to_string(Image.open(os.path.join(filename)), config=config)
text = ftfy.fix_text(text)
text = ftfy.fix_encoding(text)
text = text.replace('-\n', '')
print(text)
'''
and such, but not given me data, how can I extract text from image like of invoice?
import pytesseract
pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract'
print(pytesseract.image_to_string(r'D:\examplepdf2image.png'))
def escape(html):
"""Returns the given HTML with ampersands, quotes and carets encoded."""
return mark_safe(force_unicode(html).replace('&', '&').replace('<', '<').replace('>', '>').replace('"', '"').replace("'", '''))
this a sample code put instead of trying to print text through many different variables from this to that just try to print the image itself first. Then work on how to improve from there. One last thing is that this will let python work without errors making it easy to understand as well. The second piece of code with the def escape shows how to import an html file which you have to put your pieces of code into so you change it to your liking.

Looping an OpenCV image inside a Tkinter label - using an esp32-cam

It's a loop understanding problem, I'm new to Tkinter and I don't know how the images are updated
°°°PROBLEM°°°
It is about making a program that captures images of the esp32-cam module and can visualize and use them with the urllib and Opencv libraries, in addition to displaying the images in Tkinter to make a user interface
The image updates correctly but scrolls down as shown in the images
I would like you to help me with the problem and how to anchor it where I want, use the function .place (x = 0, y = 0) in and out of the loop but the image was not updating
°°°IMAGES°°°
starting the program, the image is centered in the Tkinter window, that's fine.
first capture
when the image is refreshed at 500 milliseconds, the image is scrolled down "infinitely", as shown in the following image:
second capture
#Python v3.8.4
import tkinter as *
from PIL import Image, ImageTk
import cv2
import numpy as np
import urllib.request
url='http://192.168.0.24/picture'
delay = 1000
imgtk = [None]
def loopCapture():
imgResponse = urllib.request.urlopen (url)
imgNp =np.array(bytearray(imgResponse.read()),dtype=np.uint8)
image = cv2.imdecode (imgNp, -1)
b,g,r = cv2.split(image)
img = cv2.merge((r,g,b))
im = Image.fromarray(img)
imgtk[0] = ImageTk.PhotoImage(image = im)
capture = Label(root, image = imgtk[0]).pack()
root.after(delay, loopCapture)
root = Tk()
root.geometry("1200x700")
loopCapture()
root.mainloop()
I just needed to learn more about the tkinter library, but if anyone comes across the same question, here is the code:
capture when running the program.
from PIL import Image, ImageTk
import urllib.request
import tkinter as tk
import numpy as np
import cv2
# esp32-cam url
urlCam ='http://192.168.0.24/picture'
panel = None
root = None
def loopCamera():
imgResponse = urllib.request.urlopen (urlCam)
imgNp = np.array(bytearray(imgResponse.read()),dtype=np.uint8)
image = cv2.imdecode (imgNp, -1)
b,g,r = cv2.split(image)
img = cv2.merge((r,g,b))
im = Image.fromarray(img)
imgtk = ImageTk.PhotoImage(image = im)
panel.configure(image = imgtk)
panel.image = imgtk
panel.after(5, loopCamera)
root = tk.Tk()
root.title('car-vision')
root.geometry('1000x600')
panel = tk.Label(root)
panel.pack()
loopCamera()
root.mainloop()

Python cv2.imread() by url

i want to get images by url here on 6 and 7 lines, any help or ideas?
import urllib
import numpy as np
mkembed = ""
ourembed = ""
mkpic = cv2.imread("image.jpg")
ourpic = cv2.imread("image2.jpg")
difference = cv2.subtract(mkpic, ourpic)
b, g, r = cv2.split(difference)
if cv2.countNonZero(b) == 0 and cv2.countNonZero(g) == 0 and cv2.countNonZero(r) == 0:
print("The images are completely Equal")```
Use the following code to get an image by url with cv2:
#import necessary packages
import numpy as np
import urllib.request as urllib
import cv2
#get image by url
resp = urllib.urlopen("https://homepages.cae.wisc.edu/~ece533/images/airplane.png")
image = np.asarray(bytearray(resp.read()), dtype="uint8")
image = cv2.imdecode(image, cv2.IMREAD_COLOR)
#show image
cv2.imshow("Image", image)
cv2.waitKey()

Combining face detection and train face opencv python

I want to combine this two code to work only once, when I run the save_detected_face.py the code save faces into jpg file when detected to OpenCV CascadeClassifier, after being saved into jpg file, the train_save_face.py will automatically run whenever the process of detecting is finish.
here is my sample code: save_detected_face.py
import os
import urllib.request
import cv2
import numpy as np
from PIL import Image
path='dataset'
recognizer=cv2.face.LBPHFaceRecognizer_create();
def main():
#cap = cv2.VideoCapture("../index.htm?clientIpAddr=192.168.1.12&IsRemote=0")
a=0
cap = "http://192.168.1.43:8080/shot.jpg"
id = input('enter user id: ')
faceDetect=cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml')
sampleNum=0
while True:
a = a+1
imgResp=urllib.request.urlopen(cap)
imgNp=np.array(bytearray(imgResp.read()),dtype=np.uint8)
img=cv2.imdecode(imgNp,-1)
gray=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
faces=faceDetect.detectMultiScale(gray,1.3,5);
for(x,y,w,h) in faces:
sampleNum = sampleNum+1
cv2.rectangle(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_color)
for (ex,ey,ew,eh) in eyes:
cv2.rectangle(roi_color,(ex,ey),(ex+ew,ey+eh),(0,255,0),2)
cv2.imwrite("dataSet/User."+str(id)+"."+str(sampleNum)+".jpg",gray[y:y+h,x:x+w])
cv2.imshow('frame', img)
# Training code
def getImagesWithID(path):
imagePaths=[os.path.join(path,f) for f in os.listdir(path)]
faces=[]
IDs=[]
for imagePath in imagePaths:
faceImg=Image.open(imagePath).convert('L');
faceNp=np.array(faceImg,'uint8')
ID=int(os.path.split(imagePath)[-1].split('.')[1])
faces.append(faceNp)
IDs.append(ID)
cv2.imshow('training',faceNp)
cv2.waitKey(10)
return np.array(IDs), faces
Ids, faces=getImagesWithID(path)
recognizer.train(faces,Ids)
recognizer.save('recognizer/trainingData.yml')
if cv2.waitKey(100) & 0xff == ord('q'):
break
elif(sampleNum>20):
break
exit(0)
#
if __name__=='__main__':
main()
code for: train_save_face.py
import os
import cv2
import numpy as np
from PIL import Image
recognizer=cv2.face.LBPHFaceRecognizer_create();
path='dataset'
def getImagesWithID(path):
imagePaths=[os.path.join(path,f) for f in os.listdir(path)]
faces=[]
IDs=[]
for imagePath in imagePaths:
faceImg=Image.open(imagePath).convert('L');
faceNp=np.array(faceImg,'uint8')
ID=int(os.path.split(imagePath)[-1].split('.')[1])
faces.append(faceNp)
IDs.append(ID)
cv2.imshow('training',faceNp)
cv2.waitKey(10)
return np.array(IDs), faces
Ids, faces=getImagesWithID(path)
recognizer.train(faces,Ids)
recognizer.save('recognizer/trainingData.yml')
exit(0)
print('done training')
The save_detected_face.py works fine, but when I want to train the face it will not work.
although I wasn't sure if this is correct but it's running now.
# -*- coding: cp1252 -*-
import os
import urllib.request
import cv2
import numpy as np
from PIL import Image
recognizer=cv2.face.LBPHFaceRecognizer_create();
path='dataset'
def main():
#cap = cv2.VideoCapture("../index.htm?clientIpAddr=192.168.1.12&IsRemote=0")
a=0
cap = "http://192.168.1.43:8080/shot.jpg"
id = input('enter user id: ')
faceDetect=cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml')
sampleNum=0
while True:
a = a+1
imgResp=urllib.request.urlopen(cap)
imgNp=np.array(bytearray(imgResp.read()),dtype=np.uint8)
img=cv2.imdecode(imgNp,-1)
gray=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
faces=faceDetect.detectMultiScale(gray,1.3,5);
for(x,y,w,h) in faces:
sampleNum = sampleNum+1
cv2.rectangle(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_color)
for (ex,ey,ew,eh) in eyes:
cv2.rectangle(roi_color,(ex,ey),(ex+ew,ey+eh),(0,255,0),2)
cv2.imwrite("dataSet/User."+str(id)+"."+str(sampleNum)+".jpg",gray[y:y+h,x:x+w])
cv2.imshow('frame', img)
if cv2.waitKey(100) & 0xff == ord('q'):
break
elif(sampleNum>20):
break
exit(0)
def getImagesWithID(path):
imagePaths=[os.path.join(path,f) for f in os.listdir(path)]
faces=[]
IDs=[]
for imagePath in imagePaths:
faceImg=Image.open(imagePath).convert('L');
faceNp=np.array(faceImg,'uint8')
ID=int(os.path.split(imagePath)[-1].split('.')[1])
faces.append(faceNp)
IDs.append(ID)
cv2.imshow('training',faceNp)
cv2.waitKey(10)
return np.array(IDs), faces
Ids, faces=getImagesWithID(path)
recognizer.train(faces,Ids)
recognizer.save('recognizer/trainingData.yml')
exit(0)
print('done training')
#
if __name__=='__main__':
main()
getImagesWithID(path)

Resources