ARTICLE DETAIL

资讯详情

深耕商务建站与企业官网运营的一线实战洞察。

Python全景图切成6个面3个层级的图

Python全景图切成6个面3个层级的图 环境搭建pipinstallopencv-python numpy Pillow tqdm代码importcv2importnumpyasnpimportmathfromPILimportImageimportosimportargparseimportplatformimportsysfrompathlibimportPathfromtqdmimporttqdm# ConstantsM_PI3.14159265358979323846TARGET_WIDTH512CUBE_SIZE1296# Face transformations for cube mappingfaceTransformnp.array([[0,0],[M_PI/2,0],[M_PI,0],[-M_PI/2,0],[0,-M_PI/2],[0,M_PI/2],])# Face identifierspath_arr(f,l,b,r,u,d)defnormalize_path(path):Normalize path based on the operating system.ifplatform.system()Windows:returnpath.replace(/,\\)returnpathdefensure_dir_exists(directory):Ensure directory exists, create if it doesnt.Path(directory).mkdir(parentsTrue,exist_okTrue)defcreateCubeMapFace(in_img,face_id0,width-1,height-1,out_path):Create a cube map face from a panoramic image.in_width,in_heightin_img.shape[1],in_img.shape[0]# Pre-calculate constantsanmath.sin(M_PI/4)akmath.cos(M_PI/4)ftu,ftvfaceTransform[face_id]# Create coordinate grids for vectorized operationsy_coords,x_coordsnp.mgrid[0:height,0:width]# Calculate nx and ny using vectorized operationsnx((y_coords0.5)/height-0.5)*2*an ny((x_coords0.5)/width-0.5)*2*an# Initialize u and v arraysunp.zeros((height,width),dtypenp.float32)vnp.zeros((height,width),dtypenp.float32)# Calculate u and v based on face transformationifftv0:unp.arctan2(nx,ak)vnp.arctan2(ny*np.cos(u),ak)uftuelifftv0:dnp.sqrt(nx*nxny*ny)vM_PI/2-np.arctan2(d,ak)unp.arctan2(ny,nx)else:dnp.sqrt(nx*nxny*ny)v-M_PI/2np.arctan2(d,ak)unp.arctan2(-ny,nx)# Normalize coordinatesu/M_PI v/(M_PI/2)# Handle wrappingvnp.where(v-1,v2,v)vnp.where(v1,v-2,v)unp.where(v-1,u1,u)unp.where(v1,u1,u)unp.where(u-1,u2,u)unp.where(u1,u-2,u)# Convert to pixel coordinatesu(u/20.5)*(in_width-1)v(v/20.5)*(in_height-1)# Create remap mapsmapxu.astype(np.float32)mapyv.astype(np.float32)# Create output imageface_imgnp.empty((height,width,in_img.shape[2]),dtypein_img.dtype)# Apply remappingcv2.remap(in_img,mapx,mapy,cv2.INTER_LINEAR,face_img,borderModecv2.BORDER_CONSTANT,borderValue(0,0,0))# Create output filenamefilename1os.path.join(out_path,path_arr[face_id],l1,1,fl1_{path_arr[face_id]}_1_1.jpg)filename1normalize_path(filename1)# Ensure directory existsensure_dir_exists(os.path.dirname(filename1))# Save the imagecv2.imwrite(filename1,face_img)# Apply rotations based on face_idifface_idin[0,1,2,3]:img1Image.open(filename1)rotated_img1img1.rotate(-90)rotated_img1.save(filename1)elifface_id5:img1Image.open(filename1)rotated_img1img1.rotate(-180)rotated_img1.save(filename1)# Resize the imageresize_image_to_512px(filename1,filename1)returnfilename1defsplit_image_into_four(image_path,output_dir,word):Split an image into four equal parts.# Read the imageimagecv2.imread(image_path)ifimageisNone:print(fError: Could not read the image at{image_path})return# Get image dimensionsheight,widthimage.shape[:2]# Calculate split positionshalf_heightheight//2half_widthwidth//2# Normalize pathsoutput_dirnormalize_path(output_dir)p1normalize_path(os.path.join(output_dir,1))p2normalize_path(os.path.join(output_dir,2))# Ensure directories existensure_dir_exists(output_dir)ensure_dir_exists(p1)ensure_dir_exists(p2)# Split and save imagessplits[(image[0:half_height,0:half_width],p1,fl2_{word}_1_1.jpg),(image[0:half_height,half_width:width],p1,fl2_{word}_1_2.jpg),(image[half_height:height,0:half_width],p2,fl2_{word}_2_1.jpg),(image[half_height:height,half_width:width],p2,fl2_{word}_2_2.jpg)]forimg_part,dir_path,filenameinsplits:filepathos.path.join(dir_path,filename)cv2.imwrite(filepath,img_part)resize_image_to_512px(filepath,filepath)defsplit_image_into_nine(image_path,output_dir,word):Split an image into nine equal parts.# Read the imageimagecv2.imread(image_path)ifimageisNone:print(fError: Could not read the image at{image_path})return# Get image dimensionsheight,widthimage.shape[:2]# Calculate split positionsthird_heightheight//3third_widthwidth//3# Normalize pathoutput_dirnormalize_path(output_dir)# Ensure directory existsensure_dir_exists(output_dir)# Split and save imagesforiinrange(3):forjinrange(3):# Calculate boundariesy_starti*third_height y_end(i1)*third_height x_startj*third_width x_end(j1)*third_width# Extract sub-imagesub_imageimage[y_start:y_end,x_start:x_end]# Create output pathi_newi1j_newj1output_pathnormalize_path(os.path.join(output_dir,str(i_new)))ensure_dir_exists(output_path)# Save sub-imagefilepathos.path.join(output_path,fl3_{word}_{i_new}_{j_new}.jpg)cv2.imwrite(filepath,sub_image)resize_image_to_512px(filepath,filepath)defresize_image_to_512px(image_path,output_path):Resize an image to have a width of 512px while maintaining aspect ratio.# Read the imageimagecv2.imread(image_path)# Check if image was loaded successfullyifimageisNone:print(fError: Could not read the image at{image_path})return# Get image dimensionsheight,widthimage.shape[:2]# Calculate new dimensionsaspect_ratioheight/width target_heightint(TARGET_WIDTH*aspect_ratio)# Resize imageresized_imagecv2.resize(image,(TARGET_WIDTH,target_height))# Save resized imagecv2.imwrite(output_path,resized_image)defprocess_panoramic_image(input_image_path):Process a panoramic image into cube map faces and tiles.# Read the input imagesrc_imagecv2.imread(input_image_path)ifsrc_imageisNone:print(fError: Could not read the image at{input_image_path})returnFalse# Flip the image horizontallysrc_imagecv2.flip(src_image,1)# Set cube dimensionswidth,heightCUBE_SIZE,CUBE_SIZE# Create output directory pathout_diros.path.dirname(input_image_path)out_fnameos.path.basename(input_image_path).split(.)[0]out_alnormalize_path(os.path.join(out_dir,out_fname))# Process each face of the cubeforiintqdm(range(6),descProcessing cube faces):# Create cube map faceface_imgcreateCubeMapFace(src_image,i,width,height,out_al)# Get face identifierwordpath_arr[i]# Split face into tilessplit_image_into_four(face_img,os.path.join(out_al,word,l2),word)split_image_into_nine(face_img,os.path.join(out_al,word,l3),word)# Set directory permissionsos.chmod(out_al,0o755)returnTrueif__name____main__:# Parse command line argumentsparserargparse.ArgumentParser(descriptionProcess panoramic images into cube map faces and tiles.)parser.add_argument(input_image,typestr,helpPath to the input panoramic image file.)argsparser.parse_args()# Process the imagesuccessprocess_panoramic_image(args.input_image)# Exit with appropriate status codesys.exit(0ifsuccesselse1)代码运行命令python cutimg.py 图片路径
返回列表
PREV
查看更多资讯
NEXT
返回资讯列表