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()