1.图像取反
import cv2 as cv
# 索引是[i,j,k] 这样写的 而不是[i:j:k] 这样写的
def access_pixels(img):
s = img.shape
for i in range(s[0]):
for j in range(s[1]):
for k in range(s[2]):
# print(i, j, k)
pv = img[i, j, k]
img[i, j, k] = 255 - pv
# cv.imshow("input", img)
# cv.imwrite("leda_covert.jpg", img)
# cv.waitKey(0)
# cv.destroyAllWindows()
if __name__ == "__main__":
src = cv.imread("leda.jpg")
t1 = cv.getTickCount()
access_pixels(src)
t2 = cv.getTickCount()
time = (t2-t1)/cv.getTickFrequency()
print(time)
import cv2 as cv
def invert():
img = cv.imread("leda.jpg")
dst = cv.bitwise_not(img)
cv.imshow("input",dst)
cv.waitKey(0)
cv.destroyAllWindows()
if __name__ == "__main__":
invert()
import cv2 as cv
#分别把图象转化成 rgb gray hsv三种三踩空间并展示
def color_space(img):
rgb = cv.cvtColor(img,cv.COLOR_BGR2RGB)
cv.namedWindow("RGB",cv.WINDOW_AUTOSIZE)
cv.imshow("RGB",rgb)
gray = cv.cvtColor(img,cv.COLOR_BGR2GRAY)
cv.namedWindow("gray", cv.WINDOW_AUTOSIZE)
cv.imshow("gray",gray)
hsv = cv.cvtColor(img,cv.COLOR_BGR2HSV)
cv.namedWindow("hsv", cv.WINDOW_AUTOSIZE)
cv.imshow("hsv",hsv)
if __name__ == "__main__":
src = cv.imread("leda.jpg")
color_space(src)
cv.waitKey(0)
cv.destroyAllWindows()
import cv2 as cv
def split_channel(img):
b,g,r = cv.split(img)
cv.namedWindow("b", cv.WINDOW_AUTOSIZE)
cv.imshow("b", b)
cv.namedWindow("g", cv.WINDOW_AUTOSIZE)
cv.imshow("g", g)
cv.namedWindow("r", cv.WINDOW_AUTOSIZE)
cv.imshow("r",r)
src = cv.merge([b,g,r])
cv.namedWindow("src", cv.WINDOW_AUTOSIZE)
cv.imshow("src", src)
if __name__ == "__main__":
src = cv.imread("leda.jpg")
split_channel(src)
cv.waitKey(0)
cv.destroyAllWindows()
5. 自定义三通道图像
import cv2 as cv
import numpy as np
def create_img():
src = np.zeros([400, 400, 3],np.uint8)
src[:, :, 0] = np.ones([400, 400]) * 255
src[:, :, 1] = np.ones([400, 400]) * 255
src[:, :, 2] = np.ones([400, 400]) * 255
src1 = np.zeros([400,400,1],np.uint8)
src1[:,:,0] = np.ones([400,400])*127
# print(src.shape)
cv.imshow("src", src)
cv.imshow("src1", src1)
if __name__ == "__main__":
create_img()
cv.waitKey(0)
cv.destroyAllWindows()