How to write PILcode with opencv - python

from PIL import Image, ImageDraw, ImageFilter
im_rgb = Image.open('x.JPG')
im_a = Image.open('blackandwhitex.png').convert('L').resize(im_rgb.size)
im_rgba = im_rgb.copy()
im_rgba.putalpha(im_a)
im_rgba.save('xtransparent.png')
Thanks to this code I made transparent on blacka and put another photo on it, so in the end I have transparent background.
How it will be look like in opencv. I need open cv, because PIL rotate photos. But it is hard to write this for someone new in opencv and google colab.
I've made transparent black using this code:
import cv2
file_name = "x.png"
src = cv2.imread(file_name, 1)
tmp = cv2.cvtColor(src, cv2.COLOR_BGR2GRAY)
_,alpha = cv2.threshold(tmp,0,255,cv2.THRESH_BINARY)
b, g, r = cv2.split(src)
rgba = [b,g,r, alpha]
dst = cv2.merge(rgba,4)
cv2.imwrite("newx.png", dst)
It's not so good...
After puttingc togehter second and third photo I want this:
It is the input of using PIL. (All images have the same size.)

Show color photo:
%pylab inline
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
img2=mpimg.imread('colorphoto.JPG')
imgplot = plt.imshow(img2)
plt.show()
Some photos are flipped after that.
Show black and white photo:
%pylab inline
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
img2=mpimg.imread('bawphoto.png')
imgplot = plt.imshow(img2)
plt.show()
For some of the photos I need to use:
from PIL import Image
def rotate(image_path, saved_location):
image_obj = Image.open(image_path)
transposed = image_obj.transpose(Image.ROTATE_90)
transposed = transposed.transpose(Image.ROTATE_180)
transposed.save(saved_location)
transposed.show()
if __name__ == '__main__':
image = 'colorphoto.JPG'
rotate(image, 'rotated_colorphoto.JPG')
And after that I convert them into one photo:
from PIL import Image, ImageDraw, ImageFilter
im_rgb = Image.open('rotated_colorphoto.JPG')
im_a = Image.open('bawphoto.png').convert('L').resize(im_rgb.size)
im_rgba = im_rgb.copy()
im_rgba.putalpha(im_a)
im_rgba.save('imagewithtransparentbackground.png')
I don't want flipped photos. I need them original size not flipped..

Related

How to show image in grayscale

for some reason this isn't working.
i may be making a silly mistake somewhere.
please help
# importing modules
import urllib.request
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import numpy as np
from PIL import Image
#dowload mona lisa image
urllib.request.urlretrieve(
'https://upload.wikimedia.org/wikipedia/commons/thumb/e/ec/Mona_Lisa%2C_by_Leonardo_da_Vinci%2C_from_C2RMF_retouched.jpg/1024px-Mona_Lisa%2C_by_Leonardo_da_Vinci%2C_from_C2RMF_retouched.jpg',
"Mona_Lisa.png")
#open the file
img = Image.open("/content/Mona_Lisa.png")
#convert to from rgba to rgb
rgb_image = img.convert('RGB')
rgb_image_rgb = np.array(rgb_image)
#show image
plt.imshow(rgb_image_rgb, cmap = cm.Greys_r)
have you tried this answer ?
How can I convert an RGB image into grayscale in Python?
from PIL import Image
img = Image.open('image.png').convert('L')
img.save('greyscale.png')
you can convert the image to grayscale using PIL.Image.convert:
img = Image.open("/content/Mona_Lisa.png").convert("L")

Colourize a grayscale image using Pillow

I have a grayscale image created using Pillow – it's mode L – and I'd like to save it as shades of a single colour, so that instead of shades from black-to-white, it's shades from cyan-to-white.
So, say I was doing this:
from PIL import Image, ImageOps
i = Image.open("old_img.jpg")
g = ImageOps.grayscale(i)
g.save("new_img.jpg")
What could I do to save it as cyan-to-white, rather than black-to-white? I'm going to do similar with other grayscale images for magenta-to-white and yellow-to-white too.
Convert your image to the "L" mode (luminosity, grayscale), and then use the .colorize() method instead of the .grayscale() one:
from PIL import Image, ImageOps
i = Image.open("old_img.jpg").convert("L")
g = ImageOps.colorize(i, black="cyan", white="white")
g.save("new_img.jpg")
or just add the command
g = ImageOps.colorize(g, black="cyan", white="white")
after applying the .grayscale(i) method (because it converts the image to the "L" mode, too):
from PIL import Image, ImageOps
i = Image.open("old_img.jpg")
g = ImageOps.grayscale(i)
g = ImageOps.colorize(g, black="yellow", white="white")
g.save("new_img.jpg")
You may set other desired color in the black= parameter of the .colorize() method.
You might be able to do that with matplotlib.imshow:
from PIL import Image, ImageOps
import matplotlib.pyplot as plt
import numpy as np
i = Image.open("frog.jpg")
g = ImageOps.grayscale(i)
fig, ax = plt.subplots(1, 1)
ax.imshow(np.array(g), cmap=plt.cm.Blues)
plt.show()
Result:

Python invert colors

I need to invert the colors of an image in Python using PIL, the problem is that I only have to invert the colors of the right half of the image and I don't know how to do it. Here is an example of how the image should look like.
And here is the code I made, bot it invert the colors of all the image.
from PIL import Image
import numpy as np
import matplotlib.pyplot as plt
import PIL.ImageOps
image_file = Image.open("Abbildung1.jpg")
image_file.load()
image_data = np.asarray(image_file, dtype=np.uint8)
inverted_image = PIL.ImageOps.invert(image_file)
inverted_image.save("neuesBild.jpg")
You can use numpy to make two parts of the image then apply the transformation and finally combine it.
from PIL import Image
import numpy as np
import matplotlib.pyplot as plt
import PIL.ImageOps
image_file = Image.open("some_image.jpeg")
image_file.load()
image_data = np.asarray(image_file, dtype=np.uint8)
width = image_data.shape[1]
left_half = image_data[:,0:width//2, :]
right_half = image_data[:,width//2:, :]
inverted_image_right = np.asarray(PIL.ImageOps.invert(Image.fromarray(right_half)))
total_image = np.hstack((left_half, inverted_image_right))
inverted_image = Image.fromarray(total_image)
inverted_image.save("invertion_half.jpeg")
That's it:
from PIL import Image
import PIL.ImageOps
img = Image.open('img.png').convert('RGB')
img.paste(ImageOps.invert(img.crop((img.width/2,0,img.width,img.height))),box=(int(img.width/2),0))
We have croped, inverted and pasted this croped-inverted image back.
Then you can check:
img.show()

Load RGB images as a ndarray, and plot out with color change

I tried to load and plot several images(jpg) from a local folder, and found out the plotting images changed color. The color channel correction between OpenCV and Matplotlib has been done.
How did it happen? How to correct the color?
Thanks.
import cv2
from matplotlib import pyplot as plt
import numpy as np
import os
folder = 'New_Web_Image'
img_list = np.empty([0,32,32,3])
for file in os.listdir(folder):
img = cv2.imread(os.path.join(folder, file))
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
img = cv2.resize(img, (32,32), interpolation = cv2.INTER_AREA)
#plt.imshow(img)
#plt.show()#If I plot the image here, the image show right color
img_list = np.append(img_list, [img[:, :, :]], axis=0)
print(img_list.shape) #lists shape check right
plt.imshow(img_list[0])
plt.show() #If I plor the image from the lists, the color changed
Here is the image result in the loop:
Here is the image from ndarray "lists":
It's not a color correction. OpenCV orders layers as BGR, rather than the RGB we usually expect. As long as you're staying with the OpenCV world, that should be fine. But anding and image loaded via cv2.imread() to matplotlib.pyplot steps outside that world, which is why you need
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
to get the layers reordered first.
A bunch of other interesting (and possibly useful) conversions are possible. See http://docs.opencv.org/3.2.0/df/d9d/tutorial_py_colorspaces.html
To halfly answer my own question, I've corrected the colors by
loading the images with a ndarray output first,
and then changing color & size, and plotting the images
Updated code:
import cv2
from matplotlib import pyplot as plt
import numpy as np
import os
# Load the images
folder = 'New_Web_Image'
img_list = []
for file in os.listdir(folder):
img = cv2.imread(os.path.join(folder, file))
if img is not None:
img_list.append(img)
img_list = np.asarray(img_list)
# Plot the images
n = img_list.shape[0]
fig, axs = plt.subplots(1, n, figsize=(20,5), dpi=80)
for i in range(n):
img = img_list[i]
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
img = cv2.resize(img, (32,32), interpolation = cv2.INTER_AREA)
axs[i].imshow(img)
plt.show()
Another half question, that "how did the color change in previous code?" is still unclear to me.
Thanks in advance to who would suggest.

How to crop the background from an inclined image?

The input is an image(document) from the scanner and my task is to crop the background and return only the document, just like this: Input Output
I've done this through thresholding and getbbox:
import matplotlib.pyplot as plt
import matplotlib.image as pli
from skimage.filters import threshold_otsu as otsu
from PIL import Image
cnh_gray = Image.open("cnh.jpg").convert('L')
cnh_gray.save('cnhgray.jpg')
img = pli.imread('cnhgray.jpg')
imagem = Image.open('cnhgray.jpg')
thresh = otsu(img)
mask = img < thresh
msk = Image.fromarray(mask,'L')
box = msk.getbbox()
crop = imagem.crop(box)
The problem is: The getbbox function doesn't work when the document isn't vertical. Since I don't know the angle, how can I rotate the image to use the getbbox funcion? If there's another function that I can use for inclined images instead of getbbox, please tell me.
Thanks for the help.

Categories

Resources