OpenCV (Open Source Computer Vision Library) is a powerful library used for a wide range of image and video processing tasks. The following are some of the most frequently used functions in the Python OpenCV library:
Basic Operations
-
cv2.imread()
- Loads an image from a file.
cv2.imread(path, flag)
- Example:
img = cv2.imread('image.jpg', cv2.IMREAD_COLOR)
-
cv2.imshow()
- Displays an image in a window.
cv2.imshow(window_name, image)
- Example:
cv2.imshow('image', img)
-
cv2.imwrite()
- Saves an image to a specified file.
cv2.imwrite(filename, img)
- Example:
cv2.imwrite('output.jpg', img)
-
cv2.cvtColor()
- Converts an image from one color space to another.
cv2.cvtColor(src, code)
- Example:
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
Image Processing
-
cv2.resize()
- Resizes an image.
cv2.resize(src, dsize[, dst[, fx[, fy[, interpolation]]]])
- Example:
resized = cv2.resize(img, (100, 100))
-
cv2.blur()
- Blurs an image using a specific window.
cv2.blur(src, ksize)
- Example:
blurred = cv2.blur(img, (5, 5))
-
cv2.Canny()
- Edge detection.
cv2.Canny(image, threshold1, threshold2[, edges[, apertureSize[, L2gradient]]])
- Example:
edges = cv2.Canny(gray, 50, 150)
-
cv2.threshold()
- Applies a fixed-level threshold to each array element.
cv2.threshold(src, thresh, maxval, type)
- Example:
ret, thresh = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)
Geometric Transformations
-
cv2.warpAffine()
- Applies an affine transformation to an image.
cv2.warpAffine(src, M, dsize)
- Example:
rotated = cv2.warpAffine(img, M, (cols, rows))
-
cv2.getRotationMatrix2D()
- Creates a matrix for rotation.
cv2.getRotationMatrix2D(center, angle, scale)
- Example:
M = cv2.getRotationMatrix2D((cols/2,rows/2), 90, 1)
Feature Detection
-
cv2.findContours()
- Finds contours in a binary image.
cv2.findContours(image, mode, method)
- Example:
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
-
cv2.drawContours()
- Draws contours on an image.
cv2.drawContours(image, contours, contourIdx, color[, thickness[, lineType[, hierarchy[, maxLevel[, offset]]]]])
- Example:
cv2.drawContours(img, contours, -1, (0,255,0), 3)
These functions represent just a snapshot of what you can do with OpenCV in Python. Depending on the specific requirements of a project, you might use many other functions provided by this comprehensive library.