I've tried a simple way to run open >> save:
PLT: open >> (new >> paste) >> save is okay to output , of course
Then I've tried the second way:
PLT: open >> (new >> paste) >> plt.save is in incorrect
sample code:
import matplotlib.pyplot as plt
from PIL import Image
image = Image.open(path)
rgbImage = Image.new("RGB", image.size)
rgbImage.paste(image)
rgbImage.save('foo.jpg')
once I tried, the error color and scale would be like this.
plt.imsave('result.jpg', rgbImage)
How can I do convert?
plt.imsave is not workable with PIL ?
Related
I am trying to run a OCR function in the background while displaying the findings in a GUI.
The OCR is working fine, but I can't seem to get the GUI started.
I think the issues is that there is not function to start the GUI, but I have not would a solution.
import time
import cv2
import mss
import numpy
import pytesseract
import matplotlib.pyplot as plt
import pandas as pd
from PIL import Image
import PySimpleGUI as sg
import os
import threading
from concurrent.futures import ThreadPoolExecutor
from PIL import Image
import pytesseract
pytesseract.pytesseract.tesseract_cmd = 'C:\\Program Files\\Tesseract-OCR\\tesseract.exe'
def ocr_function():
with mss.mss() as mss_instance:
mon = mss_instance.monitors[0]
screenshot = mss_instance.grab(mon) #Read all monitor(s)
with mss.mss() as sct:
while True:
im = numpy.asarray(sct.grab(mon))
plt.imshow(cv2.cvtColor(im, cv2.COLOR_BGR2RGB))
text = pytesseract.image_to_string(im) #image to text
time.sleep(5) #One screenshot per 5 seconds
os.system('cls') #Clear output
print(text) #Print the output text
return text #Return text to function
#plt.show()
Output = ocr_function
t = threading.Thread(target=ocr_function) #Create a thread for the OCR function
t.start() #Start the OCR thread
Output = df.sort_values(by=['Match_Acc.','D-level', 'R-level'], ascending=[False, False, False]) # Sort columes
Output = Output[Output['Match_Acc.'] >= 1]
font = ('Areal', 11)
sg.theme('BrownBlue')
data = Output
headings = ['Result', 'Column1','Column2','Column3','D-level','R-level','n_matches','nan','nonnan','Match_Acc.']
df = pd.DataFrame(data)
headings = df.columns.tolist()
data = df.values.tolist()
layout = [[sg.Table(data, headings=headings, justification='left', key='-TABLE-')],
[sg.Button('Run'), sg.Button('Exit')]]
sg.Window("Overview", layout).read(close=True)
I need help to make the pytesseract could select or choose folder or location to save the outputt result.
This is the code that I use
from tkinter import filedialog
import pytesseract as tess
from PIL import Image
tess.pytesseract.tesseract_cmd = r"C:\Program Files\Tesseract-OCR\tesseract.exe"
def extract():
files = filedialog.askopenfilenames(title="Select Images")
text = []
n = len(files)
for i in range(0,n):
img = Image.open(files[i])
text.append(tess.image_to_pdf_or_hocr(img, lang='nld', config='--psm 11 --oem 3'))
text_files = open(f'test{i+1}.pdf',"+wb")
text_files.write(text[i])
if __name__ == "__main__":
extract()
I don't have python background but eager to learn more.
Thanks
I have try few code but still not working.
Even better if someone could write and add the code to make it works
I'm very new to coding and was coping this code from a youtube video I saw subbing in my own files for images when necessary. I got to the final step of testing the ai on new images and getting a result but this error message pops up.
dir_path = "/content/drive/MyDrive/darth_vader_Bing_images/test 1"
for i in os.listdir(dir_path ):
image = img.load_img(dir_path+'//'+ i)
plt.imshow(img)
plt.show
Sample code
from PIL import Image
import matplotlib.pyplot as plt
img = Image.open('cat1.jpeg')
plt.imshow(img)
I have an image that shows the text "Cafnote". Pytesseract recognizes this, and correctly sets the variable text = "Cafnote". I then check to see if text == 'Cafnote', and if it is, I want to print "Cafnote Found!", but right now the if statement returns false. How would I get this if statement to return true?
import PIL
from cv2 import cv2
import pytesseract
import time
while 1 < 6:
time.sleep(1)
screenshot = pyautogui.screenshot('screenshot.png', region=(1441,198,219,48))
img = cv2.imread(r'screenshot.png')
median = cv2.medianBlur(img,7)
text = pytesseract.image_to_string(median)
print(text)
if text == 'Cafnote':
print("Cafnote Found!")
I found out from here that I can create and save animated GIFs using Pillow. However, it doesn't look like the save method returns any value.
I can save the GIF to a file and then open that file using Image.open, but that seems unnecessary, given that I don't really want the GIF to be saved.
How can I save the GIF to a variable, rather than a file?
That is, I would like to be able to do some_variable.show() and display a GIF, without ever having to save the GIF onto my computer.
To avoid writing any files, you can just save your image to BytesIO object. For example:
#!/usr/bin/env python
from __future__ import division
from PIL import Image
from PIL import ImageDraw
from io import BytesIO
N = 25 # number of frames
# Create individual frames
frames = []
for n in range(N):
frame = Image.new("RGB", (200, 150), (25, 25, 255*(N-n)//N))
draw = ImageDraw.Draw(frame)
x, y = frame.size[0]*n/N, frame.size[1]*n/N
draw.ellipse((x, y, x+40, y+40), 'yellow')
# Saving/opening is needed for better compression and quality
fobj = BytesIO()
frame.save(fobj, 'GIF')
frame = Image.open(fobj)
frames.append(frame)
# Save the frames as animated GIF to BytesIO
animated_gif = BytesIO()
frames[0].save(animated_gif,
format='GIF',
save_all=True,
append_images=frames[1:], # Pillow >= 3.4.0
delay=0.1,
loop=0)
animated_gif.seek(0,2)
print ('GIF image size = ', animated_gif.tell())
# Optional: display image
#animated_gif.seek(0)
#ani = Image.open(animated_gif)
#ani.show()
# Optional: write contents to file
animated_gif.seek(0)
open('animated.gif', 'wb').write(animated_gif.read())
In the end, variable animated_gif contains contents of the following image:
However, displaying an animated GIF in Python is not very reliable. ani.show() from the code above displays only first frame on my machine.