"No one is harder on a talented person than the person themselves" - Linda Wilkinson ; "Trust your guts and don't follow the herd" ; "Validate direction not destination" ;

July 06, 2022

OpenCV Notes

Color channels

  • Hue: Measures the color of the pixel.
  • Saturation: Measures the intensity of color of the pixel.
  • Value: Measures the brighness of the pixel.

Hue range

  • Red (0-60)
  • Yellow (60-120)
  • Green (120-180)
  • Cyan (180-240)
  • Blue (240-300)
  • Magenta (300-360)

RGB Channels

  • (0,0,0) is a black color.
  • (255,0,0) is a pure red color.
  • (0,255,0) is a pure green color.

#import the libraries
import cv2 as cv
import numpy as np
#read the image
img = cv.imread(r"E:\5.jpg")
#convert the BGR image to HSV colour space
hsv = cv.cvtColor(img, cv.COLOR_BGR2HSV)
cv.imshow("hsv", hsv)
cv.waitKey(0)
hsv[:,:,2] = 200 # Changes the V value
cv.imshow("hsv", hsv)
cv.waitKey(0)
rgbimg = cv.cvtColor(hsv, cv.COLOR_HSV2RGB)
cv.imshow("rgbimg", rgbimg)
cv.waitKey(0)
view raw hsvexample1.py hosted with ❤ by GitHub

 

Smoothing Functions

  • Image Smoothing - convolving the image with a low-pass filter kernel. It is useful for removing noise
  • Bilateral filter - replaces the intensity of each pixel with a weighted average of intensity values. cv.bilateralFilter() is highly effective in noise removal while keeping edges sharp


#https://docs.opencv.org/4.x/d4/d13/tutorial_py_filtering.html
import cv2 as cv
import numpy as np
from matplotlib import pyplot as plt
img = cv.imread('opencv-logo-white.png')
blur = cv.blur(img,(5,5))
import cv2 as cv
import numpy as np
from matplotlib import pyplot as plt
img = cv.imread('opencv-logo-white.png')
blur = cv.bilateralFilter(img,9,75,75)
#Adding (blending) two images using OpenCV
#https://docs.opencv.org/3.4/d5/dc4/tutorial_adding_images.html
src1 = cv.imread(cv.samples.findFile('LinuxLogo.jpg'))
src2 = cv.imread(cv.samples.findFile('WindowsLogo.jpg'))
beta = (1.0 - alpha)
dst = cv.addWeighted(src1, alpha, src2, beta, 0.0)

Color Codes

Mask for custom color range


#https://stackoverflow.com/questions/60152862/highlight-areas-with-different-colour-image-with-the-area-that-surround-them
import cv2
import numpy as np
# Load image
image = cv2.imread(r"E:\2.jpg")
# Color threshold
#(hMin = 0 , sMin = 0, vMin = 105), (hMax = 179 , sMax = 255, vMax = 255)
original = image.copy()
hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
lower = np.array([0, 0, 105])
upper = np.array([179, 255, 255])
mask = cv2.inRange(hsv, lower, upper)
result = cv2.bitwise_and(original,original,mask=mask)
cv2.imshow('mask', mask)
cv2.imshow('result', result)
cv2.imshow('original', original)
cv2.waitKey(0)
cv2.destroyAllWindows()
def nothing(x):
pass
def findranges():
# Create a window
cv2.namedWindow('image')
# Create trackbars for color change
# Hue is from 0-179 for Opencv
cv2.createTrackbar('HMin', 'image', 0, 179, nothing)
cv2.createTrackbar('SMin', 'image', 0, 255, nothing)
cv2.createTrackbar('VMin', 'image', 0, 255, nothing)
cv2.createTrackbar('HMax', 'image', 0, 179, nothing)
cv2.createTrackbar('SMax', 'image', 0, 255, nothing)
cv2.createTrackbar('VMax', 'image', 0, 255, nothing)
# Set default value for Max HSV trackbars
cv2.setTrackbarPos('HMax', 'image', 179)
cv2.setTrackbarPos('SMax', 'image', 255)
cv2.setTrackbarPos('VMax', 'image', 255)
# Initialize HSV min/max values
hMin = sMin = vMin = hMax = sMax = vMax = 0
phMin = psMin = pvMin = phMax = psMax = pvMax = 0
while(1):
# Get current positions of all trackbars
hMin = cv2.getTrackbarPos('HMin', 'image')
sMin = cv2.getTrackbarPos('SMin', 'image')
vMin = cv2.getTrackbarPos('VMin', 'image')
hMax = cv2.getTrackbarPos('HMax', 'image')
sMax = cv2.getTrackbarPos('SMax', 'image')
vMax = cv2.getTrackbarPos('VMax', 'image')
# Set minimum and maximum HSV values to display
lower = np.array([hMin, sMin, vMin])
upper = np.array([hMax, sMax, vMax])
# Convert to HSV format and color threshold
hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
mask = cv2.inRange(hsv, lower, upper)
result = cv2.bitwise_and(image, image, mask=mask)
# Print if there is a change in HSV value
if((phMin != hMin) | (psMin != sMin) | (pvMin != vMin) | (phMax != hMax) | (psMax != sMax) | (pvMax != vMax) ):
print("(hMin = %d , sMin = %d, vMin = %d), (hMax = %d , sMax = %d, vMax = %d)" % (hMin , sMin , vMin, hMax, sMax , vMax))
phMin = hMin
psMin = sMin
pvMin = vMin
phMax = hMax
psMax = sMax
pvMax = vMax
# Display result image
cv2.imshow('image', result)
if cv2.waitKey(10) & 0xFF == ord('q'):
break
cv2.destroyAllWindows()
findranges()
#https://gist.github.com/BIGBALLON/cb6ab73f6aaaa068ab6756611bb324b2
from PIL import Image, ImageOps
import os
from collections import defaultdict
import cv2
class padimages:
def padding(self,img, expected_size):
desired_size = expected_size
delta_width = desired_size - img.size[0]
delta_height = desired_size - img.size[1]
pad_width = delta_width // 2
pad_height = delta_height // 2
padding = (pad_width, pad_height, delta_width - pad_width, delta_height - pad_height)
return ImageOps.expand(img, padding)
def resize_with_padding(self,img, expected_size):
delta_width = expected_size[0] - img.size[0]
delta_height = expected_size[1] - img.size[1]
pad_width = int(delta_width // 2)
pad_height = int(delta_height // 2)
padding = (pad_width, pad_height, delta_width - pad_width, delta_height - pad_height)
return ImageOps.expand(img, padding)
imgresizer = padimages()
images_path = r'E:\Dataset_July_22\Input'
results_path = r'E:\Dataset_July_22\Results'
file_names=[]
for (dirpath, dirnames, filenames) in os.walk(images_path):
file_names.append(filenames)
print(file_names)
for file_nms in file_names:
for file_name in file_nms:
input_path = images_path + '/' + '/' + file_name
result_path = results_path + '/' + '/Res_' + file_name
print(input_path)
img = Image.open(input_path)
width, height = img.size
maxval = width
if height > width:
maxval = height
img = imgresizer.resize_with_padding(img, (maxval, maxval))
img.save(result_path)
view raw imagepadding.py hosted with ❤ by GitHub

Keep Thinking!!!!

No comments: