How to change the HSV values of an image in python? - python

I am able to convert an image from the RGB to HSV colorspace, but how can I then manipulate those values using the HSV scale as outlined in the PIL documentation?
img = Image.open("assets/image.png")
img = img.convert('HSV')
img.show()

You can convert the image to a NumPy array and manipulate it from there.
For example, to shift the hue:
import numpy as np
from PIL import image
def hue_shift(img, amount):
hsv_img = img.convert('HSV')
hsv = np.array(hsv_img)
hsv[..., 0] = (hsv[..., 0]+amount) % 360
new_img = Image.fromarray(hsv, 'HSV')
return new_img.convert('RGB')

If you get HSV images, you can use opencv library.
import argparse.
import cv2
ap = argparse.ArgumentParser()
ap.add_argument("-i", "-image", required = True, help = "Path to the image");
args = vars(ap.parse_args());
image = cv2.imread(args["image"]);
hsv = cv2.cvtColor(image, cv2.COLOR_RGB2HSV)

Related

Convert series of images into an array using OpenCV and convert the RGB array to gray scale

Hi I'm trying to convert a series of images into an array and then convert the RGB to gray scale.
In my work folder I have x number of frames.png, I need to read all this frames in an array and then convert each frame (RGB) to Gray scale.
For one frame my code is:
import numpy as np
import cv2 as cv
from PIL import Image
# Read image
Image = cv.imread('frame0.png')
# RGB to Gray Scale
GS = cv.cvtColor(Image, cv.COLOR_BGR2GRAY)
th, Gray = cv.threshold(GS, 128, 192, cv.THRESH_OTSU)
Any idea?
You can use os to read files from a folder. With the "endswith" function, you can extract file formats and pull them all.
Here is a working code
import numpy as np
import cv2 as cv
import os
for file in os.listdir("/mydir"): # images folder path
if file.endswith((".png",".jpg")): # you can add formats
img = cv.imread(file)
GS = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
th, Gray = cv.threshold(GS, 128, 192, cv.THRESH_OTSU)
cv.imwrite("converted-"+file,Gray)

Trying to save image from numpy array with PIL, getting errors

trying to save an inverted image, saved inverted RGB colour data in array pixelArray, then converted this to a numpy array. Not sure what is wrong but any help is appreciated.
from PIL import Image
import numpy as np
img = Image.open('image.jpg')
pixels = img.load()
width, height = img.size
pixelArray = []
for y in range(height):
for x in range(width):
r, g, b = pixels[x, y]
pixelArray.append((255-r,255-b,255-g))
invertedImageArray = np.array(pixelArray, dtype=np.uint8)
invertedImage = Image.fromarray(invertedImageArray, 'RGB')
invertedImage.save('inverted-image.jpeg')
img.show()
getting error code "ValueError : not enough image data"
Your np.array creates an array shape (4000000, 3) instead of (2000, 2000, 3).
Also, you may find that directly mapping the subtraction to the NumPy array is faster and easier
from PIL import Image
import numpy as np
img = Image.open('image.jpg')
pixelArray = np.array(img)
pixelArray = 255 - pixelArray
invertedImageArray = np.array(pixelArray, dtype=np.uint8)
invertedImage = Image.fromarray(invertedImageArray, 'RGB')
invertedImage.save('inverted-image.jpeg')
PIL already provides an easier way to invert the image colours with the ImageOps module.
from PIL import Image, ImageOps
img = Image.open('image.jpg')
invertedImage = ImageOps.invert(img)
invertedImage.save('inverted-image.jpeg')

Why is openCV mask turning the whole image black?

The first image is the original, the second is the hsv, and the third is the mask.
The yellowest color in the hsv image is between the boundaries set. Why is the whole image turning black?
import numpy as np
import cv2
import imutils
directory = r"C:\\Users\\colin\\Documents\\projects\\dataset\\"
i = 0
for entry in os.scandir(directory):
if (entry.path.endswith(".png")) and (i == 0):
img = cv2.imread(directory + str(entry.name))
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
i += 1
lower_range = np.array([27,132,156])
upper_range = np.array([33,138,162])
mask = cv2.inRange(hsv, lower_range, upper_range)
cv2.imwrite('C:\\Users\\colin\\Documents\\projects\\mask.png',mask)
It's all about your color ranges, you can either change the values manually and randomly or maybe take a look at this color seperator script it can be very helpful hsv color seperator

Numpy, PIL doesn't invert PNG image

I was doing a course which taught data science; it had a portion on using NumPy arrays for image inversion. It's able to invert jpg, but isn't able to invert PNG, I tried other images with the same extension, it doesn't work on those which have "png" extension (it only shows a transparent image).
What can be the problem? Thank you!
from PIL import Image
from IPython.display import display
#displaying the image
img = Image.open(r"./download.png")
display(img)
#converting the image into an array
imgArray = np.array(img)
imgArrayShape = imgArray.shape
#inverting the image
fullArray = np.full(imgArrayShape, 255)
invertedImageArray = abs(fullArray - imgArray)
invertedImageArray = invertedImageArray.astype(np.uint8)
#displaying the inverted image
invertedImage = Image.fromarray(invertedImageArray)
display(invertedImage)
As far as I could tell, the problem was, that you inverted the Alpha Channel as well.
The following code adaptation works on my end:
from PIL import Image
import numpy as np
#displaying the image
img = Image.open("test.png")
img.show()
#converting the image into an array
imgArray = np.array(img)
imgArrayShape = imgArray.shape
#inverting the image
fullArray = np.full(imgArrayShape, [255, 255, 255, 0])
invertedImageArray = abs(fullArray - imgArray)
invertedImageArray = invertedImageArray.astype(np.uint8)
#displaying the inverted image
invertedImage = Image.fromarray(invertedImageArray)
invertedImage.show()

An alternative to read image from scipy to cv2

the following python script I want to convert using opencv python, how do I make it converted?
script: scipy.misc.imread(path, mode='RGB').astype(np.float)
I want to convert it using cv2 and what would be alternative for astype(np.float) with this?
import cv2
import scipy.misc
img = scipy.misc.imread(path, mode='RGB').astype(np.float)
You may use cv2.imread, convert color format from BGR to RGB, and convert to float:
path = 'chelsea.png'
ref_img = scipy.misc.imread(path, mode='RGB').astype(np.float)
img = cv2.imread(path) # Read input imgae
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) # Convert color format form BGR to RGB (OpenCV default is BGR).
img = img.astype(np.float) # Convert ot float
print(np.all(img == ref_img))
This should do the trick:
img = cv2.imread(path, -1).astype(np.float)

Categories

Resources