Commit 580cf343 authored by josh's avatar josh
Browse files

image slicing function

parent b5d05c63
import cv2
import pathlib
def meanshiftSegmentation( image ):
pass
def sliceImage( imagePath: str, newFileBase: str, newSize: tuple, newPath: str=False ) -> int:
'''
Creates slices of images given
imagePath : path to image used for slicing
newFileBase: used to rename each slice
newSize : width and height of new slices
newPath : where to save new slices, cwd by default
returns: dictionary containing the following information
{
"pixelsLost": int,
"sliceCount": int,
"slicePaths": list
}
OR empty dictionary if slicing was unable to be completed
'''
if not newPath:
newPath = pathlib.Path.cwd()
else:
newPath = pathlib.Path( newPath )
image = cv2.imread( imagePath )
print( image.shape )
width = image.shape[0]
height = image.shape[1]
newWidth = newSize[0]
newHeight = newSize[1]
# return empty dictionary if desired slice is larger than image
if newWidth > width or newHeight > height:
return {}
# all slices will be uniform, meaning
maxWidth = ( width // newWidth ) * newWidth
maxHeight = ( height // newHeight ) * newHeight
# return data
pixelsLost = ( width - maxWidth ) + ( height - maxHeight )
newSliceCount = 0
newPaths = []
# process image
for i in range( 0, maxWidth, newWidth ):
for j in range( 0, maxHeight, newHeight ):
slicePath = newPath.joinpath( "{}_{}-{}.jpg".format( newFileBase, i, j ) )
newSliceCount += 1
newPaths.append( slicePath )
cv2.imwrite( str( slicePath ),
image[i:i+newWidth,
j:j+newHeight, :] )
return {
"pixelsLost": pixelsLost,
"sliceCount": newSliceCount,
"slicePaths": newPaths
}
if __name__ == "__main__":
cwd = pathlib.Path.cwd()
imgPath = cwd.joinpath( "GeoEye_After011310.jpg" )
newFileBase = "GeoEye_Slice"
newPath = cwd.joinpath( "sliced_images" )
sliceImage( str( imgPath ), newFileBase, ( 512, 512 ), newPath=str( newPath ) )
\ No newline at end of file
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment