SQL Server餐厅点餐系统:事务下单+JSON解析+库存原子扣减
2026/10/27 10:58:22
pipinstallopencv-python numpy Pillow tqdmimportcv2importnumpyasnpimportmathfromPILimportImageimportosimportargparseimportplatformimportsysfrompathlibimportPathfromtqdmimporttqdm# ConstantsM_PI=3.14159265358979323846TARGET_WIDTH=512CUBE_SIZE=1296# Face transformations for cube mappingfaceTransform=np.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 doesn't."""Path(directory).mkdir(parents=True,exist_ok=True)defcreateCubeMapFace(in_img,face_id=0,width=-1,height=-1,out_path=""):"""Create a cube map face from a panoramic image."""in_width,in_height=in_img.shape[1],in_img.shape[0]# Pre-calculate constantsan=math.sin(M_PI/4)ak=math.cos(M_PI/4)ftu,ftv=faceTransform[face_id]# Create coordinate grids for vectorized operationsy_coords,x_coords=np.mgrid[0:height,0:width]# Calculate nx and ny using vectorized operationsnx=((y_coords+0.5)/height-0.5)*2*an ny=((x_coords+0.5)/width-0.5)*2*an# Initialize u and v arraysu=np.zeros((height,width),dtype=np.float32)v=np.zeros((height,width),dtype=np.float32)# Calculate u and v based on face transformationifftv==0:u=np.arctan2(nx,ak)v=np.arctan2(ny*np.cos(u),ak)u+=ftuelifftv>0:d=np.sqrt(nx*nx+ny*ny)v=M_PI/2-np.arctan2(d,ak)u=np.arctan2(ny,nx)else:d=np.sqrt(nx*nx+ny*ny)v=-M_PI/2+np.arctan2(d,ak)u=np.arctan2(-ny,nx)# Normalize coordinatesu/=M_PI v/=(M_PI/2)# Handle wrappingv=np.where(v<-1,v+2,v)v=np.where(v>1,v-2,v)u=np.where(v<-1,u+1,u)u=np.where(v>1,u+1,u)u=np.where(u<-1,u+2,u)u=np.where(u>1,u-2,u)# Convert to pixel coordinatesu=(u/2+0.5)*(in_width-1)v=(v/2+0.5)*(in_height-1)# Create remap mapsmapx=u.astype(np.float32)mapy=v.astype(np.float32)# Create output imageface_img=np.empty((height,width,in_img.shape[2]),dtype=in_img.dtype)# Apply remappingcv2.remap(in_img,mapx,mapy,cv2.INTER_LINEAR,face_img,borderMode=cv2.BORDER_CONSTANT,borderValue=(0,0,0))# Create output filenamefilename1=os.path.join(out_path,path_arr[face_id],'l1','1',f'l1_{path_arr[face_id]}_1_1.jpg')filename1=normalize_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]:img1=Image.open(filename1)rotated_img1=img1.rotate(-90)rotated_img1.save(filename1)elifface_id==5:img1=Image.open(filename1)rotated_img1=img1.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 imageimage=cv2.imread(image_path)ifimageisNone:print(f"Error: Could not read the image at{image_path}")return# Get image dimensionsheight,width=image.shape[:2]# Calculate split positionshalf_height=height//2half_width=width//2# Normalize pathsoutput_dir=normalize_path(output_dir)p1=normalize_path(os.path.join(output_dir,'1'))p2=normalize_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,f'l2_{word}_1_1.jpg'),(image[0:half_height,half_width:width],p1,f'l2_{word}_1_2.jpg'),(image[half_height:height,0:half_width],p2,f'l2_{word}_2_1.jpg'),(image[half_height:height,half_width:width],p2,f'l2_{word}_2_2.jpg')]forimg_part,dir_path,filenameinsplits:filepath=os.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 imageimage=cv2.imread(image_path)ifimageisNone:print(f"Error: Could not read the image at{image_path}")return# Get image dimensionsheight,width=image.shape[:2]# Calculate split positionsthird_height=height//3third_width=width//3# Normalize pathoutput_dir=normalize_path(output_dir)# Ensure directory existsensure_dir_exists(output_dir)# Split and save imagesforiinrange(3):forjinrange(3):# Calculate boundariesy_start=i*third_height y_end=(i+1)*third_height x_start=j*third_width x_end=(j+1)*third_width# Extract sub-imagesub_image=image[y_start:y_end,x_start:x_end]# Create output pathi_new=i+1j_new=j+1output_path=normalize_path(os.path.join(output_dir,str(i_new)))ensure_dir_exists(output_path)# Save sub-imagefilepath=os.path.join(output_path,f'l3_{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 imageimage=cv2.imread(image_path)# Check if image was loaded successfullyifimageisNone:print(f"Error: Could not read the image at{image_path}")return# Get image dimensionsheight,width=image.shape[:2]# Calculate new dimensionsaspect_ratio=height/width target_height=int(TARGET_WIDTH*aspect_ratio)# Resize imageresized_image=cv2.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_image=cv2.imread(input_image_path)ifsrc_imageisNone:print(f"Error: Could not read the image at{input_image_path}")returnFalse# Flip the image horizontallysrc_image=cv2.flip(src_image,1)# Set cube dimensionswidth,height=CUBE_SIZE,CUBE_SIZE# Create output directory pathout_dir=os.path.dirname(input_image_path)out_fname=os.path.basename(input_image_path).split('.')[0]out_al=normalize_path(os.path.join(out_dir,out_fname))# Process each face of the cubeforiintqdm(range(6),desc="Processing cube faces"):# Create cube map faceface_img=createCubeMapFace(src_image,i,width,height,out_al)# Get face identifierword=path_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 argumentsparser=argparse.ArgumentParser(description='Process panoramic images into cube map faces and tiles.')parser.add_argument('input_image',type=str,help='Path to the input panoramic image file.')args=parser.parse_args()# Process the imagesuccess=process_panoramic_image(args.input_image)# Exit with appropriate status codesys.exit(0ifsuccesselse1)python cutimg.py 图片路径