import cv2
img = cv2.imread('image00.jpg', 1) #参数为 1 表示彩色
img1 = cv2.imread('image00.jpg', 0) #参数为 0 表示灰度
print(img.shape)
print(img1.shape)
cv2.waitKey()
cv2.destroyAllWindows()
结果为:
(164, 219, 3)
(164, 219)
图像类型转换详解
import cv2
img = cv2.imread("image00.jpg",1)
dst = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) #颜色空间转换
cv2.imshow('dst',dst)
cv2.waitKey()
cv2.destroyAllWindows()
import cv2
import numpy as np
img = cv2.imread('image00.jpg',1)
info = img.shape
height = info[0]
width = info[1]
dst = np.zeros((height,width,3),np.uint8)
for i in range(height):
for j in range(width):
(b,g,r) = img[i,j]
gray = (int(b)+int(g)+int(r))/3 #结果如下图左
#gray = (b+g+r) / 3 #结果如下图右
dst[i,j] = int(gray)
cv2.imshow('dst',dst)
cv2.waitKey()
cv2.destroyAllWindows()
import cv2
import numpy as np
img = cv2.imread('image00.jpg',1)
info = img.shape
height = info[0]
width = info[1]
dst = np.zeros((height,width,3),np.uint8)
# gray = r*0.299 + g*0.587 + b*0.114
for i in range(height):
for j in range(width):
(b,g,r) = img[i,j]
gray = int(b)*0.299 + int(g)*0.587 + int(r)*0.114
dst[i,j] = int(gray)
cv2.imshow('dst',dst)
cv2.waitKey()
cv2.destroyAllWindows()
import cv2
import numpy as np
img = cv2.imread('image00.jpg',1)
info = img.shape
height = info[0]
width = info[1]
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
#dst = np.zeros(img.shape,np.uint8)
dst = np.zeros((height,width,1),np.uint8)
for i in range(height):
for j in range(width):
graypixel = gray[i,j]
dst[i,j] = 255 - graypixel
cv2.imshow('dst',dst)
cv2.waitKey()
cv2.destroyAllWindows()
import cv2
import numpy as np
img = cv2.imread('image00.jpg',1)
info = img.shape
height = info[0]
width = info[1]
dst = np.zeros(img.shape,np.uint8)
for i in range(height):
for j in range(width):
(b,g,r) = img[i,j]
dst[i,j] = (255-b,255-g,255-r)
cv2.imshow('dst',dst)
cv2.waitKey()
cv2.destroyAllWindows()
import cv2
import numpy as np
img = cv2.imread('image0.jpg',1)
info = img.shape
height = info[0]
width = info[1]
for m in range(100,300):
for n in range(100,200):
# pixel -> 10*10
if m%10 == 0 and n%10 == 0:
for i in range(0,10):
for j in range(0,10):
(b,g,r) = img[m,n]
img[i+m,j+n] = (b,g,r)
cv2.imshow('dst',img)
cv2.waitKey()
cv2.destroyAllWindows()
import cv2
import numpy as np
import random
img = cv2.imread('image0.jpg',1)
info = img.shape
height = info[0]
width = info[1]
dst = np.zeros(img.shape,np.uint8)
#cv2.imshow('dst',dst)
mm = 8
for m in range(height-mm):
for n in range(width-mm):
index = int(random.random()*8)
(b,g,r) = img[m+index,n+index]
dst[m,n] = (b,g,r)
cv2.imshow('dst',dst)
cv2.waitKey()
cv2.destroyAllWindows()
import cv2
import numpy as np
img1 = cv2.imread('image0.jpg',1)
img2 = cv2.imread('image1.jpg',1)
info = img1.shape
height = info[0]
width = info[1]
#ROI
roiH = int(height/2)
roiW = int(width/2)
img1ROI = img1[0:roiH,0:roiW]
img2ROI = img2[0:roiH,0:roiW]
dst = np.zeros((roiH,roiW,3),np.uint8)
dst = cv2.addWeighted(img1ROI,0.5,img2ROI,0.5,0)
cv2.imshow('dst',dst)
cv2.waitKey()
cv2.destroyAllWindows()