opencv+Python is used to learn the basic operation of image processing. Now it is sorted out as follows, as learning notes and forgetting records.
1. Picture loading
You can read the picture from the local path and get its size:
import cv2 img = cv2.imread('Tree.jpg') shape = img.shape
The results are as follows:
2. Picture modification
The modification of a picture is essentially the modification of the pixels in the picture.
Here we do a simple processing of the picture: we cut the picture vertically and horizontally to construct a three segment picture effect.
Vertical:
img2 = img.copy() img2[0:int(shape[0]/3),:,0]=0 img2[int(shape[0]/3):int(shape[0]*2/3),:,1]=0 img2[int(shape[0]*2/3):,:,2]=0
Horizontal:
img3 = img.copy() img3[:,:int(shape[1]/3),0]=0 img3[:,int(shape[1]/3):int(shape[1]*2/3),1]=0 img3[:,int(shape[1]*2/3):,2]=0
Through the above processing, we get two new pictures, in which img2 divides the picture into three segments vertically, each segment sets the pixels on the blue, green and red channels to 0, and img3 divides into three segments horizontally.
3. Picture display
After the second step, the next step is to see the effect.
Set two display windows to display two pictures respectively, and press "s" to save two pictures, or press "ESC" to close the picture window:
cv2.namedWindow('w1',1) cv2.namedWindow('w2',1) while(1): cv2.imshow('w1',img3) cv2.imshow('w2',img2) # cv2.waitKey(25) # cv2.imshow('TreeShow',img2) if cv2.waitKey(1) & 0xFF == 27: break elif cv2.waitKey(1) & 0xFF == ord('s'): cv2.imwrite('img2.jpg',img2) cv2.imwrite('img3.jpg',img3) cv2.destroyAllWindows()
The results are as follows:
The completion code is as follows:
# -*- coding: utf-8 -*- import cv2 import numpy as np img = cv2.imread('Tree.jpg') shape = img.shape img2 = img.copy() img2[0:int(shape[0]/3),:,0]=0 img2[int(shape[0]/3):int(shape[0]*2/3),:,1]=0 img2[int(shape[0]*2/3):,:,2]=0 img3 = img.copy() img3[:,:int(shape[1]/3),0]=0 img3[:,int(shape[1]/3):int(shape[1]*2/3),1]=0 img3[:,int(shape[1]*2/3):,2]=0 cv2.namedWindow('w1',1) cv2.namedWindow('w2',1) while(1): cv2.imshow('w1',img3) cv2.imshow('w2',img2) if cv2.waitKey(1) & 0xFF == 27: break elif cv2.waitKey(1) & 0xFF == ord('s'): cv2.imwrite('img2.jpg',img2) cv2.imwrite('img3.jpg',img3) cv2.destroyAllWindows()