opencv像素的读取和像素的写入:
import cv2
img = cv2.imread('xx.jpg',1) #相对路径,读取彩色图片
(b,g,r)=img[100][100] #RGB图像在opencv读取的顺序是BGR
print(b,g,r) #打印坐标在(100,100)的像素值
#10 10 ->110 110
for i in range(1,100):
img[10+i,10+i]=(255,0,0)
cv2.imshow('image',img)#第一参数,图像的名称,第二参数,要写入的图像
cv2.waitKey(0) #cv2.waitKey(1000) 1000ms
cv2.destroyAllWindows()
等比例缩放:
#load 2info 3resize 4check
import cv2
print("------------图片的缩放---------------")
img = cv2.imread("xx.jpg",1)
cv2.imshow("Image0",img)
imgInfo = img.shape
#矩阵的shape属性可以打印矩阵的各种信息,img就是一个矩阵
print(imgInfo)
height = imgInfo[0] #h
width = imgInfo[1] #w
mode = imgInfo[2] #图片的颜色组成方式 rgb
#1放大 缩小 2等比例 非等比例
#等比例缩放
dstHeight = int(height*0.5)
dstWidth = int(width*0.5)
dst = cv2.resize(img,(dstHeight,dstWidth))
#第一个参数,需要缩放的图片,缩放后图片的HW
cv2.imshow("Image1",dst)
cv2.waitKey(0)
cv2.destroyAllWindows()
双线性变换不理解!!!
图片的剪切
import cv2
print("-----------图片剪切-----------")
img = cv2.imread("xx.jpg",1)
imgInfo = img.shape
print(imgInfo)
dst = img[50:200,50:240] #目标图像
cv2.imshow("Image",img)
cv2.imshow("DstImage",dst)
cv2.waitKey(0)
cv2.destroyAllWindows()
api的方法:
import cv2
import numpy as np
print("--------------图片移位------------------")
img = cv2.imread("xx.jpg",1)
cv2.imshow("Image",img)
imgInfo = img.shape #获取图像信息
height = imgInfo[0]
widht = imgInfo[1]
###
matShift = np.float32([[1,0,100],[0,1,200]])#等价于沿着x轴右移100,y移200
dst = cv2.warpAffine(img,matShift,(height,widht))
cv2.imshow("Dstage",dst)
cv2.waitKey(0)
像素处理的方法:
import cv2
import numpy as np
"""
图像处理:先行后列
(0,0)----------------------x
-
-
-
-
-
y
"""
img = cv2.imread("xx.jpg",1)
cv2.imshow("Image",img)
imgInfo = img.shape
dst = np.zeros(img.shape,np.uint8)
height = imgInfo[0]
width = imgInfo[1]
for i in range(0,height-200):
for j in range(0,width-100):
dst[i+200][j+100]=img[i][j] #原来(0,0)处的像素现在在(200,100)
cv2.imshow("Dstage",dst)
cv2.waitKey(0)
运行结果:
图片镜像:
import cv2
import numpy as np
img = cv2.imread("xx.jpg",1)
cv2.imshow("Image",img)
imgInfo = img.shape
height = imgInfo[0]
width = imgInfo[1]
deep = imgInfo[2]
print(imgInfo)
newImgInfo = (height*2,width,deep)
dst = np.zeros(newImgInfo,np.uint8)
for i in range(0,height):
for j in range(0,width):
dst[i,j]=img[i,j]#i是高度,j是宽度 上部
dst[2*height-i-1,j]=img[i,j]#下部分
for i in range(0,width):
dst[height,i]=(0,0,255)#BGR
cv2.imshow("dst",dst)
cv2.waitKey(0)
cv2.destroyAllWindows()
图片复制:(实现思路和镜像一致)
import cv2
import numpy as np
img =cv2.imread("xx.jpg",1)
cv2.imshow("Img",img)
ImgInfo = img.shape
height = ImgInfo[0]
width = ImgInfo[1]
deep = ImgInfo[2]
print(ImgInfo)
newImgInfo = (height*2,width*2,deep)
dst = np.zeros(newImgInfo,np.uint8)
for i in range(0,height):#高度i 宽度j
for j in range(0,width):
dst[i,j]=img[i,j]
dst[i,width+j]=img[i,j]
dst[height+i,j]=img[i,j]
dst[height+i,width+j]=img[i,j]
cv2.imshow("Dst",dst)
cv2.waitKey(0)
cv2.destroyAllWindows()