[python + opencv] 圖像的旋轉和分塊

在圖像處理的工作中,腳本語言用的比較多,近些年來,隨着python的發展,腳本編程變得更加easily accessible 。配合開源庫opencv, python可以用來做一些圖像處理的工作,這裏舉兩個簡單的實際用到的圖像處理的例子。


需要引入的頭文件:

import cv2
import numpy
import math
import string
import os

“圖像的旋轉”代碼:

# rotate(): rotate image
# return: rotated image object
def rotate(
	img,  #image matrix
	angle #angle of 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

“圖像的分塊”代碼:

# 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):
		for 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)
	


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章