opencv 圖片處理
opencv 圖片像素操作
- 取像素點操作
- 設置像素點
- 取圖片塊
- 分離,合并 b, g, r
import numpy as np
import cv2 as cvimg = cv.imread('/Users/guoyinhuang/Desktop/G77.jpeg')# 獲取像素值
px = img[348, 120] # 0 是y, 1 是x
print(px)blue = img[100, 100, 0]
print(blue)
cv.namedWindow('img', 0)# 更改像素值
img[100, 100] = [255, 255, 255]
print(img[100, 100])
# 更好的獲取像素值
img.item(10, 10, 2)
img.itemset((10, 10, 2), 100)vg = img.item(10, 10, 2)
print(vg)print(img.size)print(img.dtype)ball = img[708:1142, 680:930]
img[571:1005, 240:490] = ball# 分離合并 b,g,r
b, g, r = cv.split(img)
img = cv.merge((b,g,r))
print(b)b = img[:, :, 0]
img[:, :, 2] = 0
cv.imshow('img', img)
cv.waitKey(0)
cv.destoryAllWindows()
opencv 改變彩色空間
import cv2 as cv
import numpy as npflags = [i for i in dir(cv) if i.startswith('COLOR_')]
print(flags)cap = cv.VideoCapture(0)
while True:_, frame = cap.read()hsv = cv.cvtColor(frame, cv.COLOR_BGR2HSV)lower_blue = np.array([110, 50, 50])upper_blue = np.array([130, 255, 255])mask = cv.inRange(hsv, lower_blue, upper_blue)res = cv.bitwise_and(frame, frame, mask=mask)cv.imshow('frame', frame)cv.imshow('mask', mask)cv.imshow('res', res)k = cv.waitKey(5) & 0xFFif k == 27:break
cv.destroyAllWindows()
這是物體追蹤最簡單的方法, 當你學習了關于輪廓的方法, 你可以做更多豐富的事情:例如找到物體質心并利用它追蹤物體。
opencv 圖片的幾何旋轉操作
- 縮放
- 位移
- 平面旋轉
- 仿射旋轉
- 透視旋轉
import numpy as np
import cv2 as cv
from matplotlib import pyplot as pltimg = cv.imread('/Users/guoyinhuang/Desktop/G77.jpeg')
# res = cv.resize(img, None, fx=2, fy=2, interpolation=cv.INTER_CUBIC)
# cv.namedWindow('img', 0)
# # OR
# height, width = img.shape[:2]
# res = cv.resize(img, (2*width, 2*height), interpolation=cv.INTER_CUBIC)# translation
# rows, cols = img.shape[:2]
# M = np.float32([[1, 0, 100], [0, 1, 50]])
# dst = cv.warpAffine(img, M, (cols, rows))# Rotation
# rows, cols = img.shape[:2]
# M = cv.getRotationMatrix2D(((cols - 1)/2.0, (rows - 1)/2.0), 90, 1)
# dst = cv.warpAffine(img, M, (cols, rows))# Affine Transformation
rows, cols, ch = img.shape
pts1 = np.float32([[50, 50], [200, 50], [50, 200]])
pts2 = np.float32([[10, 100], [200, 50], [100, 250]])
M = cv.getAffineTransform(pts1, pts2)
dst = cv.warpAffine(img, M, (cols, rows))
plt.subplot(121), plt.imshow(img), plt.title('Input')
plt.subplot(122), plt.imshow(dst), plt.title('0utput')
plt.show()# perspective Transformation 透視旋轉
rows, cols, ch = img.shape
pts1 = np.float32([[56, 65], [368, 52], [28, 387], [389, 390]])
pts2 = np.float32([[0, 0], [300, 0], [0, 300], [300, 300]])
M = cv.getPerspectiveTransform(pts1, pts2)
dst = cv.warpPerspective(img, M, (300,300))
plt.subplot(121), plt.imshow(img), plt.title('Input')
plt.subplot(122), plt.imshow(dst), plt.title('Output')
plt.show()# cv.imshow('img', dst)
cv.waitKey(0)
cv.destroyAllWindows()