In the work of image processing, scripting language is used more, in recent years, with the development of Python, script programming becomes more easily accessible. With Open Source Library OpenCV, Python can be used to do some image processing work, here are two simple examples of actual image processing.
Header files to be introduced:
Import cv2
import numpy
Import math
Import string
import os
Image rotation Code:
# rotate (): Rotate image
# return:rotated Image Object
def rotate (
img, #image matrix
angle #angle o F rotation
):
height = img.shape[0]
width = img.shape[1]
if angle%180 = = 0:
scale = 1
elif angle %90 = 0:
scale = float (max (height, width))/min (height, width)
else:
scale = math.sqrt (POW (height,2) + Pow (width,2))/min (height, width)
#print ' scale%f\n '%scale
rotatemat = cv2.getrotationmatrix2d (WIDTH/2, HEIGHT/2), angle, scale)
rotateimg = Cv2.warpaffine (img, Rotatemat, (width, height))
#cv2. Imshow (' Rotateimg ', rotateimg)
#cv2. Waitkey (0) return
rotateimg #rotated image
Image chunking Code:
# split (): Split image into patches, and save them
# Return:null
def split (
img, #image matrix
ratio, #patch_length/image_length
N, #number of patches per line
dstpath #destination path
):
Height = img.shape[0]
width = img.shape[1]
#cv2. Imshow (Imgpath, img)
pheight = Int (ratio*height)
Pheightinterval = (height-pheight)/(n-1)
#print ' pheight:%d\n '%pheight
#print ' pheightinterval:%d\n '% Pheightinterval
pWidth = Int (ratio*width)
pwidthinterval = (width-pwidth)/(n-1)
#print ' pWidth:%d\n ' %pwidth
#print ' pwidthinterval:%d\n '%pwidthinterval
cnt = 1 for
i in range (n): to
J in range (N):
x = Pwidthinterval * I
y = pheightinterval * J
#print ' x:%d\n '%x
#print ' y:%d\n '%y
patch = img [Y:y+pheight, X:x+pwidth,:]
Cv2.imwrite (dstpath+ ' _%d '%cnt+ '. jpg ', patch);
CNT + + 1
#cv2. Imshow (' Patch ', patch)
#cv2. Waitkey (0)