so I am still new to python and I tried to use a script that create bokeh effect on an image written by someone else. Here is the repository : Bokeh-Effect-in-Image-using-Python
Here is more information about how the code works from the author: bokeh-effect-in-image-using-python
Notice that I am coding on VSCode, macOS BigSur, Python 3.9.
First I created a folder for my project then I created a virtual environment, it has been recognised by VsCode and incorporated into the project (so I have the .vscode folder with the json file), I created a python file in which I pasted the code and I downloaded the packages I needed inside the virtual environment.
I also tried to add different lines in the json file based on what I read on the web but it doesn't work.
The problem is that the code runs until it encounters lines using OpenCV package, I don't have any Traceback but the code just do nothing.
Here is what I have in the terminal.
Terminal
I tried to use print at different places and to remove certain lines which use opencv and the problem occurred each time opencv was used or when Tracker_HSV was used (if I deleted all the lines using opencv before) but I think it is because Tracker_HSV use OpenCV.
So maybe I made a mistake during the setup of the project or opencv is not working correctly, I don't know what to do.
(Sorry for my English, I am French.)
According to the information you provided, for the use of the module "opencv", it is recommended that you try the following:
Please install the module "opencv" correctly: "pip install opencv-python"
Please use the absolute path of the picture in the code here: "img = cv.imread("D:/.../Bokeh_Demo/flower.jpg")"
When importing the module "cv2", because it contains other files named "cv2", (so pylint reported some errors here, but this does not affect the execution of the code). We can use "from cv2 import cv2 as cv" to distinguish them.
Run:
Update 1:
Please check that the module "opencv" has been successfully installed in your currently selected VSCode environment:
More reference: Environment in VSCode.
Update 2:
# import cv2
from cv2 import cv2 as cv
import numpy as np
import Tracker_HSV as tr
from PIL import Image
import os
# cv2.namedWindow('mask', cv2.WINDOW_NORMAL)
cv.namedWindow('mask',cv.WINDOW_NORMAL)
cv.resizeWindow('mask',(500,500))
filename= 'flower.jpg'
cwd = os.getcwd()
name_file=os.path.splitext(filename)[0]
path_save_temp=os.path.join(cwd,'Data')
path_save_folder=os.path.join(path_save_temp,f'{name_file}_blur_data')
if not os.path.exists(path_save_folder):
os.makedirs(path_save_folder)
img = cv.imread("D:/....../test_Bokeh/Bokeh_Demo/flower.jpg")
blur = cv.GaussianBlur(img,(5,5),0)
img_hsv=cv.cvtColor(img,cv.COLOR_BGR2HSV)
file_save_blur= os.path.join(path_save_folder,'blur.png')
im_blur = cv.GaussianBlur(img,(81,81),0)
cv.imwrite(file_save_blur,im_blur)
xs,ys,w,h = cv.selectROI('mask',img)
crop_img=crop_img_true=crop_img_contour=img[ys:ys+h, xs:xs+w]
if not crop_img_true.shape[0]> 1:
crop_img_true=img
x,y,z,a,b,c=(tr.tracker(crop_img_true))
crop_img_true=cv.cvtColor(crop_img_true,cv.COLOR_BGR2HSV)
file_save_mask_inrange= os.path.join(path_save_folder,'mask inRange.png')
mask_inRange=cv.inRange(crop_img_true,(x,y,z),(a,b,c))
cv.imwrite(file_save_mask_inrange,mask_inRange)
_, threshold = cv.threshold(mask_inRange, 250, 255, cv.THRESH_BINARY)
Gauss_threshold =cv.adaptiveThreshold(threshold,255,cv.ADAPTIVE_THRESH_GAUSSIAN_C,cv.THRESH_BINARY_INV,101,10)
blank_space_black= np.zeros((crop_img_true.shape[0],crop_img_true.shape[1]),np.uint8)
blank_space_black[:]=(0)
_,contours,_ = cv.findContours(Gauss_threshold, cv.RETR_TREE, cv.CHAIN_APPROX_NONE)
maxi=cv.contourArea(contours[0])
c=[]
for cnt in contours:
if cv.contourArea(cnt)>=maxi:
maxi=cv.contourArea(cnt)
## print(cv2.contourArea(cnt))
c= cnt
file_save_contour= os.path.join(path_save_folder,'Contour.png')
cv.drawContours(crop_img_contour, c, -1, (0, 255, 0), 5)
cv.imwrite(file_save_contour,crop_img_contour)
file_save_poly= os.path.join(path_save_folder,'mask fill poly.png')
mask_poly=cv.fillConvexPoly(blank_space_black,c,(255,255,255))
cv.imwrite(file_save_poly,mask_poly)
crop_img_true=cv.cvtColor(crop_img_true,cv.COLOR_HSV2BGR)
file_save_mask_bitwise= os.path.join(path_save_folder,'mask bitwise and.png')
mask_bitwise_and = cv.bitwise_and(crop_img_true,crop_img_true,mask=mask_poly)
cv.imwrite(file_save_mask_bitwise,mask_bitwise_and)
im2= Image.open(file_save_mask_bitwise)
im2=im2.convert('RGBA')
datas=im2.getdata()
newdata=[]
for data in datas:
if data[0]== 0 and data[1]== 0 and data[2]== 0:
newdata.append((255,255,255,0))
else:
newdata.append(data)
file_save_transparent= os.path.join(path_save_folder,'transparent.png')
im2.putdata(newdata)
im2.save(file_save_transparent)
im_blur= Image.open(file_save_blur)
file_save_final= os.path.join(path_save_folder,'final.png')
im_blur.paste(im2,(xs,ys),im2)
im_blur.save(file_save_final)
im_final= Image.open(file_save_final)
im_final.show('Final Result')
cv.imshow('GaussianBlur',blur)
cv.waitKey(0)
cv.destroyAllWindows()
Related
Recently, I have been working on one of my python3 programs and then I wanted to to open a picture. Here is the code that I used to do it:
from PIL import Image
r = Image.open('C:/Users/sudam/OneDrive/Desktop/programming/python/projects/good night app/morning.png' )
r.show()
But as soon as I run this code,the windows photo viewer opens and gives and error saying that the specified file was moved. I tried googling this question but all of the answers I got only worked for python2, but not for python3.
Because you have whitespace in your path you need to use the r"string" format.
Also you need to use:
PIL.ImageShow.show(r)
to show your image.
It's also recommended to check if the file exist before opening any file.
You can do like this:
from pathlib import Path
from PIL import Image, ImageShow
path =r"C:/Users/sudam/OneDrive/Desktop/programming/python/projects/good night app/morning.png"
if Path(path).is_file():
r = Image.open(path)
ImageShow.show(r)
else:
print(f'{path} not exist')
Im back with another probably stupid question!, my new issue is the following:
im trying to save a picture from my webcam into a specific folder using OpenCV imwrite,
its not working obviously here is my code:
import cv2 as cv
cam = cv.VideoCapture(0)
s, img = cam.read()
if s:
path = r"\imgtest\selfietest.jpg"
cv.imwrite(path, img)
Any suggestions for edits or fixes?, i've tried copying the file using shutil and moving it using the same module, i also tried to use the OS module to move it but it threw an "Access Denied" error so i would prefer to not need to grant the application admin rights every time i launched it thanks in advance!!
((ALSO ASSUME I KNOW NOTHING ABOUT PYTHON))
Use a full path, forward slashes, and r'' to pass a raw path. cv2.imwrite(r"D:/....jpg", img)
Basically I'm using locateOnScreen() function, which is from pyautogui to read an image and then find in the screen by:
import os
import pathlib
import pyautogui
Image = os.path.join(os.path.sep, pathlib.Path(__file__).parent.resolve(), 'static', 'img', 'game', 'image-btn.png')
if pyautogui.locateOnScreen(BossImg, grayscale=True, confidence=0.95) != None:
print(True)
The code above works prety fine, the problem is when some users, even me because my native language is Portuguese and we have special characters in the language, and we might have some in a folder name.
Let's use this example:
In english:
C:\Users\guilh\Desktop\Folder
In Portuguese:
C:\Users\guilh\Área de Trabalho\Folder
So for some cases when we get a folder with accented characters, I'm getting the error:
Failed to read C:\Users\guilh\Área de Trabalho\Folder\image-btn.png because file is missing, has improper permissions, or is an unsupported or invalid format
But why am I gettig this error with special characters if I'm passing the path correctly with pathlib and os? If I run the same script in the English example, works perfectly.
After digging a bit in the source code of PyAutoGUI on Github, it appears that PyScreeze is used to detect an element on the screen from an image of it, and it uses openCV's imread() function to load the image.
cv2.imread() currently does not support pathnames containing Non-ASCII characters on Windows.
A pull-request has already been opened on the PyScreeze repository to use cv2.imdecode() instead of cv2.imread().
To fix this issue while waiting for the support for non-ASCII characters,
Method 1
The first option would be to modify the PyScreeze package installed (This can be annoying if anyone needs to be able to run the script easily from their computer).
- Identify the location of the PyScreeze module:
python -c "import pyscreeze; print(pyscreeze.__path__)"
- Modify __init__.py located in this folder:
Line 21,
import numpy as np
Line 166,
img_cv = cv2.imdecode(np.fromfile(img, dtype=np.uint8), LOAD_GRAYSCALE)
Line 168,
img_cv = cv2.imdecode(np.fromfile(img, dtype=np.uint8), LOAD_COLOR)
- Finally install numpy
pip install numpy
Method 2
As #SiP explained, Another possibility could be to copy the image to a temporary folder.
Something like that:
import os
import pathlib
import tempfile
import shutil
import pyautogui
Image = os.path.join(os.path.sep, pathlib.Path(__file__).parent.resolve(), 'static', 'img', 'game', 'image-btn.png')
temp_path = os.path.join(tempfile.gettempdir(), "file_name_in_ascii")
shutil.copy2(Image, temp_path)
if pyautogui.locateOnScreen(temp_path, grayscale=True, confidence=0.95) is not None:
print(True)
I'm trying to read a jpg file using Pillow (Version 3.2.0) in Jupyter notebook (Python 3.4), but it fails with the following error:
OSError: broken data stream when reading image file
I'm using the following code:
from PIL import Image
im = Image.open("/path/to/image.jpeg")
im.show()
It works fine both in the interactive Python shell and using Python 2.7 instead of 3.4.
I've followed these steps already: Using Pillow with Python 3
Anyone an idea what's going on?
Looks like you're not pointing to the directory where your photo is stored.
import os
defaultWd = os.getcwd()
defaultWd # Sets your curretn wd
os.chdir(defaultWd + '\\Desktop') # Points to your photo--e.g., on Desktop
os.getcwd() # Shows change in wd
from PIL import Image
im = Image.open("Mew.jpg")
im.show() # Will plot to your default image viewing software
And another way if you don't want to change current wd:
im = Image.open(os.getcwd() + "\\Desktop\\Mew.jpg")
im.show()
And if you want to plot inline:
from matplotlib.pyplot import imshow
%matplotlib inline
inlinePic = Image.open(os.getcwd() + "\\Desktop\\Mew.jpg")
imshow(inlinePic)
Note: You may also want to simply try typing 'jpg' instead of 'jpeg' as you did above, if your image is in your current working directory. Also, if PIC is not installed, you'll get this error NameError: name 'Image' is not defined.
The problem was related to another import: I was importing Tensorflow before PIL, which caused the problem. Same issue as this one: https://github.com/scikit-image/scikit-image/issues/2000. Changing the order of the imports solved it.
I am new to Python and tried to run the following code. I received the following error "IOError: cannot open resource". Is this due to the fact that some of the Image characteristics do not longer exist (e.g. Coval.otf), or is it potentially due to writing/reading restrictions? please let me know - many thanks, W
import numpy as np
from PIL import Image, ImageDraw, ImageFont
from skimage import transform as tf
def create_captcha(text, shear=0, size=(100,24)):
im = Image.new("L", size, "black")
draw = ImageDraw.Draw(im)
font = ImageFont.truetype(r"Coval.otf", 22)
draw.text((2, 2), text, fill=1, font=font)
image = np.array(im)
affine_tf = tf.AffineTransform(shear=shear)
image = tf.warp(image, affine_tf)
return image / image.max()
%matplotlib inline
from matplotlib import pyplot as plt
image = create_captcha("GENE", shear=0.5)
It's because Coval.otf cannot be read, probably because it doesn't exist on your system, this is specified in the ImageFont doc. I tried searching for the specific font and found no way of aquiring it. Look at #NewYork167's link if you must use the Coval font.
Either way, to save yourself the trouble of installing fonts, you could just change the call to a font that exists on your system, use the one specified in the example of the docs:
font = ImageFont.truetype("arial.ttf", 15)
For me after running the following:
conda install -c conda-forge graphviz
conda install -c conda-forge python-graphviz
and then linking the font on mac by:
img = Image.open("tree1.png")
draw = ImageDraw.Draw(img)
font = ImageFont.truetype('/Library/Fonts/Arial.ttf', 15)
It worked perfectly.
If you are using colab then you will have to provide path properly just writing arial.ttf is not sufficient.
To get the path if that font-type is available on colab :
!fc-list or !fc-list | grep ""
and then you can add the whole path.enter image description here
Looks like you can install Coval from here to save you from having to change fonts in future code as well
https://fontlibrary.org/en/font/bretan
The font files for PIL on windows are case sensitive.
Go to Windows/fonts:
Some fonts are *.tff
Others are *.TFF
You have to use the actual file name and not the font title thingy that Windows shows from control panel.
I also found that for Anaconda3 2019.03 the truetype font var is case sensitive. I'm using Windows 10, and had to look in C:\Windows\Fonts. Looking at the properties I saw the 'Arial.ttf' font was 'arial.ttf' in the explorer.
ImageFont.truetype('arial.ttf') works while
ImageFont.truetype('Arial.ttf') throws a 'cannot open resource' error.
Annoying change, but worked for me.
In my case (Centos, Python 3.6.6), the font requires absolute path like:
ttfont = ImageFont.truetype('/root/pyscripts/arial.ttf',35)
The relative path like ~/pyscripts/arial.ttf won't work.