Changing Colorspaces
To change Colorspace of an image
import numpy as np import cv2 img = cv2.imread('C:/Users/user/Desktop/python/image.jpg') # Convert BGR to HSVhsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)cv2.imshow('hsv',hsv) cv2.waitKey(0) cv2.destroyAllWindows()
To have a look at complete set of methods in OpenCV use,
flags = [i for i in dir(cv2) if i.startswith('COLOR_')]
Now try to change into different color spaces
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
Thresholding
(where the pixels are either 255 or 0)
ret, gb = cv2.threshold(img,130,255,cv2.THRESH_BINARY)
Contours
Joining same intensity
import numpy as np import cv2 img = cv2.imread('C:/Users/user/Desktop/python/image.jpg') imgray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) ret,thresh = cv2.threshold(imgray,127,255,0) im2, contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) res=cv2.drawContours(img, contours, -1, (0,0,255), 3) cv2.imshow('result',res) cv2.waitKey(0) cv2.destroyAllWindows()
Histograms
Another way of understanding the image. Intuition about contrast, brightness, intensity distribution
cv2.calcHist(images, channels, mask, histSize, ranges[,])
count = 0import numpy as np import cv2 from matplotlib import pyplot as plt img = cv2.imread('C:/Users/user/Desktop/python/image.jpg') hist = cv2.calcHist([img],[0],None,[256],[0,256]) plt.hist(img.ravel(),256,[0,256]) plt.title('Histogram for gray scale picture') plt.show()