Spaces:
Sleeping
Sleeping
ikeda commited on
Commit ·
6810bed
1
Parent(s): bc6513e
translate Japanese comments to English
Browse filesFiles changed (6)
1234518 unmodified lines242526272829305 unmodified lines3637383940414243444546474849505152535455565758596061626364656667import gradio as grfrom PIL import Image as PIL_Image # gltflibのImageと被るので別名にする。from io import BytesIOimport jsonimport os18 unmodified linesimg_bytearray = BytesIO()image['background'].save(img_bytearray, "JPEG", quality=95)img_bytearray.seek(0) # 画像の先頭にシークしないと空データになってしまう。option_dict = {'タイトル': title,5 unmodified lines'厚み': '有' if is_thick else '無',}# model_noのコード値決定ルールを接頭語を付けた場合分けやファクトリ―クラスの作成を検討した方が良いif model_no not in ['A', 'B']:# カード画像(表面)の作成if model_no == '1':front_img_bytearray = create_historic_site_card_image(img_bytearray, option_dict)else:front_img_bytearray = create_card_image(model_no, img_bytearray, option_dict)# カード画像(裏面)の取得back_path = constants.back_card_img_dict[model_no]back_img = PIL_Image.open(back_path)back_img_bytearray = BytesIO()back_img.convert('RGB').save(back_img_bytearray, "JPEG", quality=95)back_img_bytearray.seek(0) # 画像の先頭にシークしないと空データになってしまう。# カードの3Dモデルの作成(戻り値は作成したモデルのパス)model_path = create_card_model(front_img_bytearray, back_img_bytearray, option_dict)else:# 3Dモデルの作成(戻り値は作成したモデルのパス)if model_no == 'A':model_path = create_picture_box_model(img_bytearray)if model_no == 'B':model_path = create_extracted_objects_model(img_bytearray)# 作成した3Dモデルの送信return model_pathwith gr.Blocks() as demo:1234518 unmodified lines242526272829305 unmodified lines36373839404142434445464748495051525354555657585960616263646566import gradio as grfrom PIL import Image as PIL_Image # Renaming to avoid conflict with Image from gltflibfrom io import BytesIOimport jsonimport os18 unmodified linesimg_bytearray = BytesIO()image['background'].save(img_bytearray, "JPEG", quality=95)img_bytearray.seek(0) # Seek to the beginning of the image, otherwise it results in empty data.option_dict = {'タイトル': title,5 unmodified lines'厚み': '有' if is_thick else '無',}# Consider implementing model_no categorization rules or creating a factory classif model_no not in ['A', 'B']:# Create the card image (front side)if model_no == '1':front_img_bytearray = create_historic_site_card_image(img_bytearray, option_dict)else:front_img_bytearray = create_card_image(model_no, img_bytearray, option_dict)# Retrieve the card image (back side)back_path = constants.back_card_img_dict[model_no]back_img = PIL_Image.open(back_path)back_img_bytearray = BytesIO()back_img.convert('RGB').save(back_img_bytearray, "JPEG", quality=95)back_img_bytearray.seek(0) # Seek to the beginning of the image, otherwise it results in empty data# Create a 3D model of the card (return value is the path of the created model)model_path = create_card_model(front_img_bytearray, back_img_bytearray, option_dict)else:# Create a 3D model of the card (return value is the path of the created model)if model_no == 'A':model_path = create_picture_box_model(img_bytearray)if model_no == 'B':model_path = create_extracted_objects_model(img_bytearray)return model_pathwith gr.Blocks() as demo:
1234561 unmodified line89101112131415161718192 unmodified lines222324252627282930313233343536373839404157 unmodified lines991001011021031041057 unmodified lines1131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551568 unmodified lines1651661671681691701711 unmodified line1731741751761771781796 unmodified lines18618718818919019119219319419519619719819924 unmodified lines2242252262272282292302312322332342352362372382392407 unmodified lines2482492502512522532541 unmodified line25625725825926026126214 unmodified lines277278279280281282283import ioimport numpy as npfrom PIL import Image as PIL_Image # gltflibのImageと被るので別名にする。import structimport uuid1 unmodified lineGLTF, GLTFModel, Asset, Scene, Node, Mesh, Primitive, Attributes, Buffer, BufferView, Image, Texture, TextureInfo, Material, Sampler, Accessor, AccessorType,BufferTarget, ComponentType, GLBResource, PBRMetallicRoughness)# 共通設定情報# バイナリ部分のオフセットやサイズに関わらない部分は予め定義できる。# アセットasset=Asset()# イメージimages=[Image(mimeType='image/jpeg', bufferView=4),Image(mimeType='image/jpeg',bufferView=5),2 unmodified linesImage(mimeType='image/jpeg',bufferView=8),Image(mimeType='image/jpeg',bufferView=9),]# サンプラーsamplers = [Sampler(magFilter=9728, minFilter=9984)] # magFilter:最近傍フィルタリング、minFilter:ミップマップ+最近傍フィルタリング# テクスチャtextures = [Texture(name='Front',sampler=0,source=0),Texture(name='Back',sampler=0,source=1),Texture(name='Left',sampler=0,source=2), # 左Texture(name='Right',sampler=0,source=3), # 右Texture(name='Top',sampler=0,source=4), # 上Texture(name='Bottom',sampler=0,source=5), # 下]# マテリアルmaterials = [Material(pbrMetallicRoughness=PBRMetallicRoughness(57 unmodified lines),]# メッシュmeshes = [Mesh(name='Front', primitives=[Primitive(attributes=Attributes(POSITION=0, NORMAL=1,TEXCOORD_0=2), indices=3, material=0)]),Mesh(name='Back', primitives=[Primitive(attributes=Attributes(POSITION=0, NORMAL=1,TEXCOORD_0=2), indices=3, material=1)]),7 unmodified linesis_thick = True if option_dict['厚み'] == '有' else False# 表面画像front_img = PIL_Image.open(front_img_bytearray).convert('RGB')front_bytearray = io.BytesIO()front_img.save(front_bytearray, format="JPEG", quality=95) # JPEG保存を強制front_bytearray = front_bytearray.getvalue()front_bytelen = len(front_bytearray)# 裏面画像back_img = PIL_Image.open(back_img_bytearray).convert('RGB')back_bytearray = io.BytesIO()back_img.save(back_bytearray, format="JPEG", quality=95) # JPEG保存を強制back_bytearray = back_bytearray.getvalue()back_bytelen = len(back_bytearray)# 側面画像の作成(裏面の端の色を延長する)back_img_array = np.array(back_img)left_side_img = PIL_Image.fromarray(np.tile(back_img_array[:, [0], :], [1, 32, 1]))right_side_img = PIL_Image.fromarray(np.tile(back_img_array[:, [back_img_array.shape[1] - 1], :], [1, 32, 1]))top_side_img = PIL_Image.fromarray(np.tile(back_img_array[[0], :, :], [32, 1, 1]))bottom_side_img = PIL_Image.fromarray(np.tile(back_img_array[[back_img_array.shape[0] - 1], :, :], [32, 1, 1]))left_side_bytearray = io.BytesIO()left_side_img.save(left_side_bytearray, format="JPEG", quality=95) # JPEG保存を強制left_side_bytearray = left_side_bytearray.getvalue()left_side_bytelen = len(left_side_bytearray)right_side_bytearray = io.BytesIO()right_side_img.save(right_side_bytearray, format="JPEG", quality=95) # JPEG保存を強制right_side_bytearray = right_side_bytearray.getvalue()right_side_bytelen = len(right_side_bytearray)top_side_bytearray = io.BytesIO()top_side_img.save(top_side_bytearray, format="JPEG", quality=95) # JPEG保存を強制top_side_bytearray = top_side_bytearray.getvalue()top_side_bytelen = len(top_side_bytearray)bottom_side_bytearray = io.BytesIO()bottom_side_img.save(bottom_side_bytearray, format="JPEG", quality=95) # JPEG保存を強制bottom_side_bytearray = bottom_side_bytearray.getvalue()bottom_side_bytelen = len(bottom_side_bytearray)# 頂点データ(POSITION)vertices = [(-1.0, -1.0, 0.0),( 1.0, -1.0, 0.0),8 unmodified linesmins = [min([vertex[i] for vertex in vertices]) for i in range(3)]maxs = [max([vertex[i] for vertex in vertices]) for i in range(3)]# 法線データ(NORMAL)normals = [( 0.0, 0.0, 1.0)] * 4normal_bytearray = bytearray()for normal in normals:1 unmodified linenormal_bytearray.extend(struct.pack('f', value))normal_bytelen = len(normal_bytearray)# テクスチャ座標(TEXCOORD_0)texcoord_0s = [(0.0, 1.0),(1.0, 1.0),6 unmodified linestexcoord_0_bytearray.extend(struct.pack('f', value))texcoord_0_bytelen = len(texcoord_0_bytearray)# 頂点インデックスvertex_indices = [0, 1, 2, 1, 3, 2]vertex_index_bytearray = bytearray()for value in vertex_indices:vertex_index_bytearray.extend(struct.pack('H', value))vertex_index_bytelen = len(vertex_index_bytearray)# バイナリデータ部分の結合bytearray_list = [vertex_bytearray,normal_bytearray,24 unmodified linesall_bytearray = bytearray()for temp_bytearray in bytearray_list:all_bytearray.extend(temp_bytearray)offset_list = [0] + bytelen_cumsum_list # 最初のオフセットは0offset_list.pop() # 末尾を削除# リソースの作成resources = [GLBResource(data=all_bytearray)]# 各種設定# バッファbuffers = [Buffer(byteLength=len(all_bytearray))]# バッファビューbufferViews = [BufferView(buffer=0, byteOffset=offset_list[0], byteLength=bytelen_list[0], target=BufferTarget.ARRAY_BUFFER.value),BufferView(buffer=0, byteOffset=offset_list[1], byteLength=bytelen_list[1], target=BufferTarget.ARRAY_BUFFER.value),7 unmodified linesBufferView(buffer=0, byteOffset=offset_list[9], byteLength=bytelen_list[9], target=None),]# アクセサーaccessors = [Accessor(bufferView=0, componentType=ComponentType.FLOAT.value, count=len(vertices), type=AccessorType.VEC3.value, max=maxs, min=mins),Accessor(bufferView=1, componentType=ComponentType.FLOAT.value, count=len(normals), type=AccessorType.VEC3.value, max=None, min=None),1 unmodified lineAccessor(bufferView=3, componentType=ComponentType.UNSIGNED_SHORT.value, count=len(vertex_indices), type=AccessorType.SCALAR.value, max=None, min=None),]# ノードcard_thickness = 0.025card_ratio_x = 0.8679999709129333card_ratio_y = 1.213000059127807614 unmodified linesNode(mesh=1, scale=[card_ratio_x, card_ratio_y, card_ratio_z], rotation=[0, 1, 0, 0])]# シーンscene = 0if is_thick:scenes = [Scene(name='Scene', nodes=[0, 1, 2, 3, 4, 5])]1234561 unmodified line8910111213141516171819202 unmodified lines232425262728293031323334353637383940414257 unmodified lines1001011021031041051067 unmodified lines1141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561578 unmodified lines1661671681691701711721 unmodified line1741751761771781791806 unmodified lines18718818919019119219319419519619719819920024 unmodified lines2252262272282292302312322332342352362372382392407 unmodified lines2482492502512522532541 unmodified line25625725825926026126214 unmodified lines277278279280281282283import ioimport numpy as npfrom PIL import Image as PIL_Image # Renaming to avoid conflict with Image from gltflibimport structimport uuid1 unmodified lineGLTF, GLTFModel, Asset, Scene, Node, Mesh, Primitive, Attributes, Buffer, BufferView, Image, Texture, TextureInfo, Material, Sampler, Accessor, AccessorType,BufferTarget, ComponentType, GLBResource, PBRMetallicRoughness)# Common configuration information# Parts that are independent of the binary section's offset and size can be predefined.# Assetasset=Asset()# Imageimages=[Image(mimeType='image/jpeg', bufferView=4),Image(mimeType='image/jpeg',bufferView=5),2 unmodified linesImage(mimeType='image/jpeg',bufferView=8),Image(mimeType='image/jpeg',bufferView=9),]# Samplersamplers = [Sampler(magFilter=9728, minFilter=9984)] # magFilter: Nearest filtering, minFilter: Mipmap + Nearest filtering# Texturetextures = [Texture(name='Front',sampler=0,source=0),Texture(name='Back',sampler=0,source=1),Texture(name='Left',sampler=0,source=2),Texture(name='Right',sampler=0,source=3),Texture(name='Top',sampler=0,source=4),Texture(name='Bottom',sampler=0,source=5),]# Materialmaterials = [Material(pbrMetallicRoughness=PBRMetallicRoughness(57 unmodified lines),]# Meshmeshes = [Mesh(name='Front', primitives=[Primitive(attributes=Attributes(POSITION=0, NORMAL=1,TEXCOORD_0=2), indices=3, material=0)]),Mesh(name='Back', primitives=[Primitive(attributes=Attributes(POSITION=0, NORMAL=1,TEXCOORD_0=2), indices=3, material=1)]),7 unmodified linesis_thick = True if option_dict['厚み'] == '有' else False# Front imagefront_img = PIL_Image.open(front_img_bytearray).convert('RGB')front_bytearray = io.BytesIO()front_img.save(front_bytearray, format="JPEG", quality=95) # Force JPEG format for savingfront_bytearray = front_bytearray.getvalue()front_bytelen = len(front_bytearray)# Back imageback_img = PIL_Image.open(back_img_bytearray).convert('RGB')back_bytearray = io.BytesIO()back_img.save(back_bytearray, format="JPEG", quality=95) # Force JPEG format for savingback_bytearray = back_bytearray.getvalue()back_bytelen = len(back_bytearray)# Create side image (extend the color of the edges of the back side)back_img_array = np.array(back_img)left_side_img = PIL_Image.fromarray(np.tile(back_img_array[:, [0], :], [1, 32, 1]))right_side_img = PIL_Image.fromarray(np.tile(back_img_array[:, [back_img_array.shape[1] - 1], :], [1, 32, 1]))top_side_img = PIL_Image.fromarray(np.tile(back_img_array[[0], :, :], [32, 1, 1]))bottom_side_img = PIL_Image.fromarray(np.tile(back_img_array[[back_img_array.shape[0] - 1], :, :], [32, 1, 1]))left_side_bytearray = io.BytesIO()left_side_img.save(left_side_bytearray, format="JPEG", quality=95) # Force JPEG format for savingleft_side_bytearray = left_side_bytearray.getvalue()left_side_bytelen = len(left_side_bytearray)right_side_bytearray = io.BytesIO()right_side_img.save(right_side_bytearray, format="JPEG", quality=95) # Force JPEG format for savingright_side_bytearray = right_side_bytearray.getvalue()right_side_bytelen = len(right_side_bytearray)top_side_bytearray = io.BytesIO()top_side_img.save(top_side_bytearray, format="JPEG", quality=95) # Force JPEG format for savingtop_side_bytearray = top_side_bytearray.getvalue()top_side_bytelen = len(top_side_bytearray)bottom_side_bytearray = io.BytesIO()bottom_side_img.save(bottom_side_bytearray, format="JPEG", quality=95) # Force JPEG format for savingbottom_side_bytearray = bottom_side_bytearray.getvalue()bottom_side_bytelen = len(bottom_side_bytearray)# Vertex data(POSITION)vertices = [(-1.0, -1.0, 0.0),( 1.0, -1.0, 0.0),8 unmodified linesmins = [min([vertex[i] for vertex in vertices]) for i in range(3)]maxs = [max([vertex[i] for vertex in vertices]) for i in range(3)]# Normal data(NORMAL)normals = [( 0.0, 0.0, 1.0)] * 4normal_bytearray = bytearray()for normal in normals:1 unmodified linenormal_bytearray.extend(struct.pack('f', value))normal_bytelen = len(normal_bytearray)# Texture coordinates(TEXCOORD_0)texcoord_0s = [(0.0, 1.0),(1.0, 1.0),6 unmodified linestexcoord_0_bytearray.extend(struct.pack('f', value))texcoord_0_bytelen = len(texcoord_0_bytearray)# Vertex indicesvertex_indices = [0, 1, 2, 1, 3, 2]vertex_index_bytearray = bytearray()for value in vertex_indices:vertex_index_bytearray.extend(struct.pack('H', value))vertex_index_bytelen = len(vertex_index_bytearray)# Concatenation of the binary data sectionbytearray_list = [vertex_bytearray,normal_bytearray,24 unmodified linesall_bytearray = bytearray()for temp_bytearray in bytearray_list:all_bytearray.extend(temp_bytearray)offset_list = [0] + bytelen_cumsum_list # The first offset is 0offset_list.pop() # Remove the end# GLBResourceresources = [GLBResource(data=all_bytearray)]# Bufferbuffers = [Buffer(byteLength=len(all_bytearray))]# BufferViewbufferViews = [BufferView(buffer=0, byteOffset=offset_list[0], byteLength=bytelen_list[0], target=BufferTarget.ARRAY_BUFFER.value),BufferView(buffer=0, byteOffset=offset_list[1], byteLength=bytelen_list[1], target=BufferTarget.ARRAY_BUFFER.value),7 unmodified linesBufferView(buffer=0, byteOffset=offset_list[9], byteLength=bytelen_list[9], target=None),]# Accessoraccessors = [Accessor(bufferView=0, componentType=ComponentType.FLOAT.value, count=len(vertices), type=AccessorType.VEC3.value, max=maxs, min=mins),Accessor(bufferView=1, componentType=ComponentType.FLOAT.value, count=len(normals), type=AccessorType.VEC3.value, max=None, min=None),1 unmodified lineAccessor(bufferView=3, componentType=ComponentType.UNSIGNED_SHORT.value, count=len(vertex_indices), type=AccessorType.SCALAR.value, max=None, min=None),]# Nodecard_thickness = 0.025card_ratio_x = 0.8679999709129333card_ratio_y = 1.213000059127807614 unmodified linesNode(mesh=1, scale=[card_ratio_x, card_ratio_y, card_ratio_z], rotation=[0, 1, 0, 0])]# Scenescene = 0if is_thick:scenes = [Scene(name='Scene', nodes=[0, 1, 2, 3, 4, 5])]
1234563 unmodified lines10111213141516171819202122232425263 unmodified lines303132333435363738394041426 unmodified lines49505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989912 unmodified lines1121131141151161171181191201212 unmodified lines1241251261271281291301311321331341351361373 unmodified lines14114214314414514614714814915015115215314 unmodified lines1681691701711721731741751761771781791801811821831841851861872 unmodified lines1901911921931941951961 unmodified line1981992002012022032042052062072082092102112122132142152162177 unmodified lines225226227228229230231232233234235236237238239240241242243244245import ioimport numpy as npfrom PIL import Image as PIL_Image # gltflibのImageと被るので別名にする。import cv2import structimport triangle3 unmodified linesGLTF, GLTFModel, Asset, Scene, Node, Mesh, Primitive, Attributes, Buffer, BufferView, Image, Texture, TextureInfo, Material, Sampler, Accessor, AccessorType,BufferTarget, ComponentType, GLBResource, PBRMetallicRoughness)# 表面及び裏面の頂点リストの作成def make_front_and_back_vertex_list(coordinate_list, img):# 表面の頂点front_vertex_list = []# 裏面の頂点back_vertex_list = []for coordinates in coordinate_list:front_vertices = []back_vertices = []# Y軸方向は画像とGLBで上下が逆になるので注意for coordinate in coordinates:front_vertices.append((coordinate[0] * 2 / img.size[0] - 1.0, -(coordinate[1] * 2 / img.size[1] - 1.0), 0.2))back_vertices.append((coordinate[0] * 2 / img.size[0] - 1.0, -(coordinate[1] * 2 / img.size[1] - 1.0), -0.2))3 unmodified linesreturn front_vertex_list, back_vertex_list# メッシュの各種情報の作成def make_mesh_data(coordinate_list, img):front_vertex_list, back_vertex_list = make_front_and_back_vertex_list(coordinate_list, img)# 頂点データ(POSITION)vertices = []# 頂点インデックス決定時に使うオフセット値のリストfront_offset = 0front_offset_list = []back_offset_list = []6 unmodified linesback_offset_list.append(back_offset)front_offset += len(front_vertices) + len(back_vertices)# 法線データ(NORMAL)normals = []for front_vertices, back_vertices in zip(front_vertex_list, back_vertex_list):normals.extend([( 0.0, 0.0, 1.0)] * len(front_vertices))normals.extend([( 0.0, 0.0, -1.0)] * len(back_vertices))# テクスチャ座標(TEXCOORD_0)# 画像は左上原点になり、Y軸の上下を変える必要がある。texcoord_0s = [((vertex[0] + 1.0) / 2.0, 1.0 - ((vertex[1] + 1.0) / 2.0) ) for vertex in vertices]# 頂点インデックスvertex_indices = []for front_vertices, back_vertices, front_offset, back_offset \in zip(front_vertex_list, back_vertex_list, front_offset_list, back_offset_list):polygon = {'vertices': np.array(front_vertices)[:, :2],'segments': np.array([( i, (i + 1) % (len(front_vertices)) ) for i in range(len(front_vertices))]) # 各辺を定義}triangulate_result = triangle.triangulate(polygon, 'p')vertex_indices.extend(list(np.array(triangulate_result['triangles']+front_offset).flatten())) # 表面vertex_indices.extend(list((np.array(triangulate_result['triangles'])+back_offset).flatten())) # 裏面vertex_indices.extend(list(np.array([[front_offset + i,front_offset + (i + 1) % len(front_vertices),back_offset + i]for i in range(len(front_vertices))]).flatten())) # 側面1vertex_indices.extend(list(np.array([[back_offset + i,back_offset + (i + 1) % len(back_vertices),front_offset+ (i + 1) % len(front_vertices)] for i in range(len(front_vertices))]).flatten())) # 側面2return vertices, normals, texcoord_0s, vertex_indicesdef create_extracted_objects_model(img_bytearray):# 画像の取得img = PIL_Image.open(img_bytearray).convert('RGB')img_bytearray = io.BytesIO()img.save(img_bytearray, format="JPEG", quality=95)img_bytearray = img_bytearray.getvalue()img_bytelen = len(img_bytearray)# 3Dモデルのスケールの計算scale_factor = np.power(img.size[0] * img.size[1], 0.5)scale = (img.size[0] / scale_factor, img.size[1] / scale_factor, 0.4)# 画像主要部分の頂点の取得base_color = img.getpixel((0, 0))mask = PIL_Image.new('RGB', img.size)for i in range(img.size[0]):12 unmodified linescoordinates.append((x, y))coordinate_list.append(coordinates)# 各種データの作成vertices, normals, texcoord_0s, vertex_indices = make_mesh_data(coordinate_list, img)# 頂点データ(POSITION)vertex_bytearray = bytearray()for vertex in vertices:for value in vertex:2 unmodified linesmins = [min([vertex[i] for vertex in vertices]) for i in range(3)]maxs = [max([vertex[i] for vertex in vertices]) for i in range(3)]# 法線データ(NORMAL)normal_bytearray = bytearray()for normal in normals:for value in normal:normal_bytearray.extend(struct.pack('f', value))normal_bytelen = len(normal_bytearray)# テクスチャ座標(TEXCOORD_0)texcoord_0s = [((vertex[0] + 1.0) / 2.0, 1.0 - ((vertex[1] + 1.0) / 2.0) ) for vertex in vertices]3 unmodified linestexcoord_0_bytearray.extend(struct.pack('f', value))texcoord_0_bytelen = len(texcoord_0_bytearray)# 頂点インデックスvertex_index_bytearray = bytearray()for value in vertex_indices:vertex_index_bytearray.extend(struct.pack('H', value))vertex_index_bytelen = len(vertex_index_bytearray)# バイナリデータ部分の結合bytearray_list = [vertex_bytearray,normal_bytearray,14 unmodified linesall_bytearray = bytearray()for temp_bytearray in bytearray_list:all_bytearray.extend(temp_bytearray)offset_list = [0] + bytelen_cumsum_list # 最初のオフセットは0offset_list.pop() # 末尾を削除# リソースの作成resources = [GLBResource(data=all_bytearray)]# 各種設定# アセットasset=Asset()# バッファbuffers = [Buffer(byteLength=len(all_bytearray))]# バッファビューbufferViews = [BufferView(buffer=0, byteOffset=offset_list[0], byteLength=bytelen_list[0], target=BufferTarget.ARRAY_BUFFER.value),BufferView(buffer=0, byteOffset=offset_list[1], byteLength=bytelen_list[1], target=BufferTarget.ARRAY_BUFFER.value),2 unmodified linesBufferView(buffer=0, byteOffset=offset_list[4], byteLength=bytelen_list[4], target=None),]# アクセサーaccessors = [Accessor(bufferView=0, componentType=ComponentType.FLOAT.value, count=len(vertices), type=AccessorType.VEC3.value, max=maxs, min=mins),Accessor(bufferView=1, componentType=ComponentType.FLOAT.value, count=len(normals), type=AccessorType.VEC3.value, max=None, min=None),1 unmodified lineAccessor(bufferView=3, componentType=ComponentType.UNSIGNED_SHORT.value, count=len(vertex_indices), type=AccessorType.SCALAR.value, max=None, min=None)]# イメージimages=[Image(mimeType='image/jpeg', bufferView=4),]# サンプラーsamplers = [Sampler(magFilter=9728, minFilter=9984)] # magFilter:最近傍フィルタリング、minFilter:ミップマップ+最近傍フィルタリング# テクスチャtextures = [Texture(name='Main',sampler=0,source=0),]# マテリアルmaterials = [Material(pbrMetallicRoughness=PBRMetallicRoughness(7 unmodified lines),]# メッシュmeshes = [Mesh(name='Main', primitives=[Primitive(attributes=Attributes(POSITION=0, NORMAL=1,TEXCOORD_0=2),indices=3, material=0, mode=4)]),]# ノードnodes = [Node(mesh=0,rotation=None, scale=scale),]# シーンscene = 0scenes = [Scene(name='Scene', nodes=[0])]model = GLTFModel(asset=asset,buffers=buffers,1234563 unmodified lines10111213141516171819202122232425263 unmodified lines303132333435363738394041426 unmodified lines49505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989912 unmodified lines1121131141151161171181191201212 unmodified lines1241251261271281291301311321331341351361373 unmodified lines14114214314414514614714814915015115215314 unmodified lines1681691701711721731741751761771781791801811821831841851862 unmodified lines1891901911921931941951 unmodified line1971981992002012022032042052062072082092102112122132142152167 unmodified lines224225226227228229230231232233234235236237238239240241242243244245import ioimport numpy as npfrom PIL import Image as PIL_Image # Renaming to avoid conflict with Image from gltflibimport cv2import structimport triangle3 unmodified linesGLTF, GLTFModel, Asset, Scene, Node, Mesh, Primitive, Attributes, Buffer, BufferView, Image, Texture, TextureInfo, Material, Sampler, Accessor, AccessorType,BufferTarget, ComponentType, GLBResource, PBRMetallicRoughness)# Create vertex lists for both the front and back surfacesdef make_front_and_back_vertex_list(coordinate_list, img):# Front surface verticesfront_vertex_list = []# Back surface verticesback_vertex_list = []for coordinates in coordinate_list:front_vertices = []back_vertices = []# Note that the Y-axis direction is inverted between the image and GLB, so be carefulfor coordinate in coordinates:front_vertices.append((coordinate[0] * 2 / img.size[0] - 1.0, -(coordinate[1] * 2 / img.size[1] - 1.0), 0.2))back_vertices.append((coordinate[0] * 2 / img.size[0] - 1.0, -(coordinate[1] * 2 / img.size[1] - 1.0), -0.2))3 unmodified linesreturn front_vertex_list, back_vertex_list# Creation of various information for the meshdef make_mesh_data(coordinate_list, img):front_vertex_list, back_vertex_list = make_front_and_back_vertex_list(coordinate_list, img)# Vertex data(POSITION)vertices = []# List of offset values used when determining vertex indicesfront_offset = 0front_offset_list = []back_offset_list = []6 unmodified linesback_offset_list.append(back_offset)front_offset += len(front_vertices) + len(back_vertices)# Normal data(NORMAL)normals = []for front_vertices, back_vertices in zip(front_vertex_list, back_vertex_list):normals.extend([( 0.0, 0.0, 1.0)] * len(front_vertices))normals.extend([( 0.0, 0.0, -1.0)] * len(back_vertices))# Texture coordinates (TEXCOORD_0)# The image origin is at the top-left, requiring an inversion of the Y-axis.texcoord_0s = [((vertex[0] + 1.0) / 2.0, 1.0 - ((vertex[1] + 1.0) / 2.0) ) for vertex in vertices]# Vertex indicesvertex_indices = []for front_vertices, back_vertices, front_offset, back_offset \in zip(front_vertex_list, back_vertex_list, front_offset_list, back_offset_list):polygon = {'vertices': np.array(front_vertices)[:, :2],'segments': np.array([( i, (i + 1) % (len(front_vertices)) ) for i in range(len(front_vertices))]) # Define each edge}triangulate_result = triangle.triangulate(polygon, 'p')vertex_indices.extend(list(np.array(triangulate_result['triangles']+front_offset).flatten())) # Front surfacevertex_indices.extend(list((np.array(triangulate_result['triangles'])+back_offset).flatten())) # Back surfacevertex_indices.extend(list(np.array([[front_offset + i,front_offset + (i + 1) % len(front_vertices),back_offset + i]for i in range(len(front_vertices))]).flatten())) # Side surface 1vertex_indices.extend(list(np.array([[back_offset + i,back_offset + (i + 1) % len(back_vertices),front_offset+ (i + 1) % len(front_vertices)] for i in range(len(front_vertices))]).flatten())) # Side surface 2return vertices, normals, texcoord_0s, vertex_indicesdef create_extracted_objects_model(img_bytearray):# Retrieve the imageimg = PIL_Image.open(img_bytearray).convert('RGB')img_bytearray = io.BytesIO()img.save(img_bytearray, format="JPEG", quality=95)img_bytearray = img_bytearray.getvalue()img_bytelen = len(img_bytearray)# Calculate the scale of the 3D modelscale_factor = np.power(img.size[0] * img.size[1], 0.5)scale = (img.size[0] / scale_factor, img.size[1] / scale_factor, 0.4)# Retrieve vertices of the main part of the imagebase_color = img.getpixel((0, 0))mask = PIL_Image.new('RGB', img.size)for i in range(img.size[0]):12 unmodified linescoordinates.append((x, y))coordinate_list.append(coordinates)# Creation of associated data for the meshvertices, normals, texcoord_0s, vertex_indices = make_mesh_data(coordinate_list, img)# Vertex data(POSITION)vertex_bytearray = bytearray()for vertex in vertices:for value in vertex:2 unmodified linesmins = [min([vertex[i] for vertex in vertices]) for i in range(3)]maxs = [max([vertex[i] for vertex in vertices]) for i in range(3)]# Normal data(NORMAL)normal_bytearray = bytearray()for normal in normals:for value in normal:normal_bytearray.extend(struct.pack('f', value))normal_bytelen = len(normal_bytearray)# Texture coordinates(TEXCOORD_0)texcoord_0s = [((vertex[0] + 1.0) / 2.0, 1.0 - ((vertex[1] + 1.0) / 2.0) ) for vertex in vertices]3 unmodified linestexcoord_0_bytearray.extend(struct.pack('f', value))texcoord_0_bytelen = len(texcoord_0_bytearray)# Vertex indicesvertex_index_bytearray = bytearray()for value in vertex_indices:vertex_index_bytearray.extend(struct.pack('H', value))vertex_index_bytelen = len(vertex_index_bytearray)# Concatenation of the binary data sectionbytearray_list = [vertex_bytearray,normal_bytearray,14 unmodified linesall_bytearray = bytearray()for temp_bytearray in bytearray_list:all_bytearray.extend(temp_bytearray)offset_list = [0] + bytelen_cumsum_list # The first offset is 0offset_list.pop() # 末尾を削除# GLBResourceresources = [GLBResource(data=all_bytearray)]# Assetasset=Asset()# Bufferbuffers = [Buffer(byteLength=len(all_bytearray))]# BufferViewbufferViews = [BufferView(buffer=0, byteOffset=offset_list[0], byteLength=bytelen_list[0], target=BufferTarget.ARRAY_BUFFER.value),BufferView(buffer=0, byteOffset=offset_list[1], byteLength=bytelen_list[1], target=BufferTarget.ARRAY_BUFFER.value),2 unmodified linesBufferView(buffer=0, byteOffset=offset_list[4], byteLength=bytelen_list[4], target=None),]# Accessoraccessors = [Accessor(bufferView=0, componentType=ComponentType.FLOAT.value, count=len(vertices), type=AccessorType.VEC3.value, max=maxs, min=mins),Accessor(bufferView=1, componentType=ComponentType.FLOAT.value, count=len(normals), type=AccessorType.VEC3.value, max=None, min=None),1 unmodified lineAccessor(bufferView=3, componentType=ComponentType.UNSIGNED_SHORT.value, count=len(vertex_indices), type=AccessorType.SCALAR.value, max=None, min=None)]# Imageimages=[Image(mimeType='image/jpeg', bufferView=4),]# Samplersamplers = [Sampler(magFilter=9728, minFilter=9984)] # magFilter:最近傍フィルタリング、minFilter:ミップマップ+最近傍フィルタリング# Texturetextures = [Texture(name='Main',sampler=0,source=0),]# Materialmaterials = [Material(pbrMetallicRoughness=PBRMetallicRoughness(7 unmodified lines),]# Meshmeshes = [Mesh(name='Main', primitives=[Primitive(attributes=Attributes(POSITION=0, NORMAL=1,TEXCOORD_0=2),indices=3, material=0, mode=4)]),]# Nodenodes = [Node(mesh=0,rotation=None, scale=scale),]# Scenescene = 0scenes = [Scene(name='Scene', nodes=[0])]# GLTFModelmodel = GLTFModel(asset=asset,buffers=buffers,
2 unmodified lines345678910111213141516171819202122232425262728298 unmodified lines383940414243444546474849505152535455565758595 unmodified lines6566676869707111 unmodified lines8384858687888990912 unmodified linesfrom src.constants import front_card_img_dict# カード画像各領域のピクセル位置情報# 写真PICTURE_LT_XY = (65, 188)PICTURE_RB_XY = (802, 925)PICTURE_SIZE = (PICTURE_RB_XY[0] - PICTURE_LT_XY[0], PICTURE_RB_XY[1] - PICTURE_LT_XY[1])# タイトル# ある程度の余白を作る。TITLE_LT_XY = (65, 45)TITLE_RB_XY = (647, 132) # マーク挿入部分と重ならないような位置TITLE_SIZE = (TITLE_RB_XY[0] - TITLE_LT_XY[0], TITLE_RB_XY[1] - TITLE_LT_XY[1])# 説明文本体DESCRIPTION_LT_XY = (46, 972)DESCRIPTION_RB_XY = (810, 1174)DESCRIPTION_SIZE = (DESCRIPTION_RB_XY[0] - DESCRIPTION_LT_XY[0], DESCRIPTION_RB_XY[1] - DESCRIPTION_LT_XY[1])# フォント関連# 明朝体font_selif_path = 'data/fonts/SourceHanSerif-Bold.otf'# ゴシック体font_sanselif_path = 'data/fonts/SourceHanSans-Bold.otf'def crop_center(pil_img, crop_width, crop_height):8 unmodified linesdef create_card_image(model_no, img_bytearray, option_dict):# 画像の読み込みとトリミングpicture_img = Image.open(img_bytearray)picture_img = crop_max_square(picture_img)picture_img = picture_img.resize(PICTURE_SIZE)# カードの読み込みcard_img = Image.open(front_card_img_dict[model_no])# 写真の埋め込みcard_img.paste(picture_img, PICTURE_LT_XY)# 各種書き込み準備card_imgdraw = ImageDraw.Draw(card_img)# タイトル埋め込み# (複数行対応は必要ならば対応)title_font_size = 100while True:title_font = ImageFont.truetype(font_selif_path, title_font_size)5 unmodified linescard_imgdraw.text((TITLE_LT_XY[0], int((TITLE_LT_XY[1] + TITLE_RB_XY[1]) / 2)), option_dict['タイトル'], fill='black', font=title_font, anchor='lm')# 説明文埋め込みdescription_font = ImageFont.truetype(font_sanselif_path, 40)description_list = []11 unmodified linescard_imgdraw.text(DESCRIPTION_LT_XY, description_display, fill='black', font=description_font)# バイナリデータの出力output_img_bytearray = BytesIO()card_img.convert('RGB').save(output_img_bytearray, "JPEG", quality=95)output_img_bytearray.seek(0) # 画像の先頭にシークしないと空データになってしまう。return output_img_bytearray2 unmodified lines345678910111213141516171819202122232425262728298 unmodified lines383940414243444546474849505152535455565758595 unmodified lines6566676869707111 unmodified lines8384858687888990912 unmodified linesfrom src.constants import front_card_img_dict# Pixel position information for each area of the card image# PicturePICTURE_LT_XY = (65, 188)PICTURE_RB_XY = (802, 925)PICTURE_SIZE = (PICTURE_RB_XY[0] - PICTURE_LT_XY[0], PICTURE_RB_XY[1] - PICTURE_LT_XY[1])# Title# Create some marginTITLE_LT_XY = (65, 45)TITLE_RB_XY = (647, 132)TITLE_SIZE = (TITLE_RB_XY[0] - TITLE_LT_XY[0], TITLE_RB_XY[1] - TITLE_LT_XY[1])# Main Body of DescriptionDESCRIPTION_LT_XY = (46, 972)DESCRIPTION_RB_XY = (810, 1174)DESCRIPTION_SIZE = (DESCRIPTION_RB_XY[0] - DESCRIPTION_LT_XY[0], DESCRIPTION_RB_XY[1] - DESCRIPTION_LT_XY[1])# Font information# Ming Typefacefont_selif_path = 'data/fonts/SourceHanSerif-Bold.otf'# Gothic Typefacefont_sanselif_path = 'data/fonts/SourceHanSans-Bold.otf'def crop_center(pil_img, crop_width, crop_height):8 unmodified linesdef create_card_image(model_no, img_bytearray, option_dict):# Loading and Cropping of Picturepicture_img = Image.open(img_bytearray)picture_img = crop_max_square(picture_img)picture_img = picture_img.resize(PICTURE_SIZE)# Loading of Card Framecard_img = Image.open(front_card_img_dict[model_no])# Embedding a Picture in the Cardcard_img.paste(picture_img, PICTURE_LT_XY)## Preparing for editting the card imagecard_imgdraw = ImageDraw.Draw(card_img)# Embedding the Title# (Support for multiple lines if needed)title_font_size = 100while True:title_font = ImageFont.truetype(font_selif_path, title_font_size)5 unmodified linescard_imgdraw.text((TITLE_LT_XY[0], int((TITLE_LT_XY[1] + TITLE_RB_XY[1]) / 2)), option_dict['タイトル'], fill='black', font=title_font, anchor='lm')# Embedding the Description Textdescription_font = ImageFont.truetype(font_sanselif_path, 40)description_list = []11 unmodified linescard_imgdraw.text(DESCRIPTION_LT_XY, description_display, fill='black', font=description_font)# Outputting Binary Dataoutput_img_bytearray = BytesIO()card_img.convert('RGB').save(output_img_bytearray, "JPEG", quality=95)output_img_bytearray.seek(0) # Seek to the beginning of the image, otherwise it results in empty datareturn output_img_bytearray
123456717 unmodified lines25262728293031323334353637383940414243444546474849505152535455565758596061628 unmodified lines71727374757677787980818283848586878889909192939495969798991001011021031041051065 unmodified lines11211311411511611711811912012112212312412512612712812913011 unmodified lines142143144145146147148149150from PIL import Image, ImageDraw, ImageFontfrom io import BytesIO# カード画像関連card_frame_path_dict = {'橙': 'data/cards/史跡カードフレーム(橙).png','白': 'data/cards/史跡カードフレーム(白).png',17 unmodified lines'都指定': 'data/cards/史跡カード指定マーク(都指定).png'}# カード画像各領域のピクセル位置情報# 写真PICTURE_LT_XY = (65, 188)PICTURE_RB_XY = (802, 925)PICTURE_SIZE = (PICTURE_RB_XY[0] - PICTURE_LT_XY[0], PICTURE_RB_XY[1] - PICTURE_LT_XY[1])# タイトル# ある程度の余白を作る。TITLE_LT_XY = (65, 45)TITLE_RB_XY = (647, 132) # マーク挿入部分と重ならないような位置TITLE_SIZE = (TITLE_RB_XY[0] - TITLE_LT_XY[0], TITLE_RB_XY[1] - TITLE_LT_XY[1])# 説明欄区切り線DESCRIPTION_LINE_L_XY = (52, 1024)DESCRIPTION_LINE_R_XY = (816, 1024)# 史跡種類HS_TYPE_LT_XY = (56, 972)# 訪問難度DIFFICULTY_LT_XY = (444, 972)# 説明文本体DESCRIPTION_LT_XY = (46, 1024)DESCRIPTION_RB_XY = (810, 1174)DESCRIPTION_SIZE = (DESCRIPTION_RB_XY[0] - DESCRIPTION_LT_XY[0], DESCRIPTION_RB_XY[1] - DESCRIPTION_LT_XY[1])# フォント関連# 明朝体font_selif_path = 'data/fonts/SourceHanSerif-Bold.otf'# ゴシック体font_sanselif_path = 'data/fonts/SourceHanSans-Bold.otf'def crop_center(pil_img, crop_width, crop_height):8 unmodified linesdef create_historic_site_card_image(img_bytearray, option_dict):# 画像の読み込みとトリミングpicture_img = Image.open(img_bytearray)picture_img = crop_max_square(picture_img)picture_img = picture_img.resize(PICTURE_SIZE)# カードの読み込みcard_img = Image.open(card_frame_path_dict[option_dict['色']])# マークの追加mark_image = Image.open(card_mark_path_dict[option_dict['マーク']])card_img.paste(mark_image, mask=mark_image)# 写真の埋め込みcard_img.paste(picture_img, PICTURE_LT_XY)# 各種書き込み準備card_imgdraw = ImageDraw.Draw(card_img)# カード枠線の追加card_imgdraw.line(( (0, 0), (card_img.size[0], 0) ), fill='black', width=15)card_imgdraw.line(( (0, 0), (0, card_img.size[1]) ), fill='black', width=15)card_imgdraw.line(( (card_img.size[0], 0), card_img.size), fill='black', width=15)card_imgdraw.line(( (0, card_img.size[1]), card_img.size), fill='black', width=15)# 説明欄区切り線の追加card_imgdraw.line((DESCRIPTION_LINE_L_XY, DESCRIPTION_LINE_R_XY), fill='black', width=3)# タイトル埋め込み# (複数行対応は必要ならば対応)title_font_size = 100while True:title_font = ImageFont.truetype(font_selif_path, title_font_size)5 unmodified linescard_imgdraw.text((TITLE_LT_XY[0], int((TITLE_LT_XY[1] + TITLE_RB_XY[1]) / 2)), option_dict['タイトル'], fill='black', font=title_font, anchor='lm')# 史跡種類埋め込みhs_type_display = f'種類:{option_dict["史跡種類"]}'hs_typefont = ImageFont.truetype(font_sanselif_path, 40)card_imgdraw.text(HS_TYPE_LT_XY, hs_type_display, fill='black', font=hs_typefont, anchor='lt')# 訪問難度埋め込みdifficulty = int(option_dict['訪問難度'])difficulty = 1 if difficulty < 1 else 5 if difficulty > 5 else difficultydifficulty_display = '訪問難度:' + '☆' * difficulty + '★' * (5 - difficulty)difficulty_font = ImageFont.truetype(font_sanselif_path, 40)card_imgdraw.text(DIFFICULTY_LT_XY, difficulty_display, fill='black', font=difficulty_font, anchor='lt')# 説明文埋め込みdescription_font = ImageFont.truetype(font_sanselif_path, 40)description_list = []11 unmodified linescard_imgdraw.text(DESCRIPTION_LT_XY, description_display, fill='black', font=description_font)# バイナリデータの出力output_img_bytearray = BytesIO()card_img.convert('RGB').save(output_img_bytearray, "JPEG", quality=95)output_img_bytearray.seek(0) # 画像の先頭にシークしないと空データになってしまう。return output_img_bytearray12345678917 unmodified lines272829303132333435363738394041424344454647484950515253545556575859606162638 unmodified lines727374757677787980818283848586878889909192939495969798991001011021031041051065 unmodified lines11211311411511611711811912012112212312412512612712812913011 unmodified lines142143144145146147148149150from PIL import Image, ImageDraw, ImageFontfrom io import BytesIO# Card image information# Historic Site Card filescard_frame_path_dict = {'橙': 'data/cards/史跡カードフレーム(橙).png','白': 'data/cards/史跡カードフレーム(白).png',17 unmodified lines'都指定': 'data/cards/史跡カード指定マーク(都指定).png'}# Pixel position information for each area of the card image# PicturePICTURE_LT_XY = (65, 188)PICTURE_RB_XY = (802, 925)PICTURE_SIZE = (PICTURE_RB_XY[0] - PICTURE_LT_XY[0], PICTURE_RB_XY[1] - PICTURE_LT_XY[1])# Title# Create some marginTITLE_LT_XY = (65, 45)TITLE_RB_XY = (647, 132) # Position to avoid overlapping with the marker insertion pointTITLE_SIZE = (TITLE_RB_XY[0] - TITLE_LT_XY[0], TITLE_RB_XY[1] - TITLE_LT_XY[1])# Explanation Section DividerDESCRIPTION_LINE_L_XY = (52, 1024)DESCRIPTION_LINE_R_XY = (816, 1024)# Historic Site TypeHS_TYPE_LT_XY = (56, 972)# Difficulty of VisitDIFFICULTY_LT_XY = (444, 972)# Main Body of DescriptionDESCRIPTION_LT_XY = (46, 1024)DESCRIPTION_RB_XY = (810, 1174)DESCRIPTION_SIZE = (DESCRIPTION_RB_XY[0] - DESCRIPTION_LT_XY[0], DESCRIPTION_RB_XY[1] - DESCRIPTION_LT_XY[1])# Font information# Ming Typefacefont_selif_path = 'data/fonts/SourceHanSerif-Bold.otf'# Gothic Typefacefont_sanselif_path = 'data/fonts/SourceHanSans-Bold.otf'def crop_center(pil_img, crop_width, crop_height):8 unmodified linesdef create_historic_site_card_image(img_bytearray, option_dict):# Loading and Cropping of Picturepicture_img = Image.open(img_bytearray)picture_img = crop_max_square(picture_img)picture_img = picture_img.resize(PICTURE_SIZE)# Loading of Card Framecard_img = Image.open(card_frame_path_dict[option_dict['色']])# Adding a Markermark_image = Image.open(card_mark_path_dict[option_dict['マーク']])card_img.paste(mark_image, mask=mark_image)# Embedding a Picture in the Cardcard_img.paste(picture_img, PICTURE_LT_XY)# Preparing for editting the card imagecard_imgdraw = ImageDraw.Draw(card_img)# Adding a Border to the Cardcard_imgdraw.line(( (0, 0), (card_img.size[0], 0) ), fill='black', width=15)card_imgdraw.line(( (0, 0), (0, card_img.size[1]) ), fill='black', width=15)card_imgdraw.line(( (card_img.size[0], 0), card_img.size), fill='black', width=15)card_imgdraw.line(( (0, card_img.size[1]), card_img.size), fill='black', width=15)# Adding a Divider Line to the Explanation Sectioncard_imgdraw.line((DESCRIPTION_LINE_L_XY, DESCRIPTION_LINE_R_XY), fill='black', width=3)# Embedding the Title# (Support for multiple lines if needed)title_font_size = 100while True:title_font = ImageFont.truetype(font_selif_path, title_font_size)5 unmodified linescard_imgdraw.text((TITLE_LT_XY[0], int((TITLE_LT_XY[1] + TITLE_RB_XY[1]) / 2)), option_dict['タイトル'], fill='black', font=title_font, anchor='lm')# Embedding the Historic Site Typehs_type_display = f'種類:{option_dict["史跡種類"]}'hs_typefont = ImageFont.truetype(font_sanselif_path, 40)card_imgdraw.text(HS_TYPE_LT_XY, hs_type_display, fill='black', font=hs_typefont, anchor='lt')# Embedding the Difficulty of Visitdifficulty = int(option_dict['訪問難度'])difficulty = 1 if difficulty < 1 else 5 if difficulty > 5 else difficultydifficulty_display = '訪問難度:' + '☆' * difficulty + '★' * (5 - difficulty)difficulty_font = ImageFont.truetype(font_sanselif_path, 40)card_imgdraw.text(DIFFICULTY_LT_XY, difficulty_display, fill='black', font=difficulty_font, anchor='lt')# Embedding the Description Textdescription_font = ImageFont.truetype(font_sanselif_path, 40)description_list = []11 unmodified linescard_imgdraw.text(DESCRIPTION_LT_XY, description_display, fill='black', font=description_font)# Outputting Binary Dataoutput_img_bytearray = BytesIO()card_img.convert('RGB').save(output_img_bytearray, "JPEG", quality=95)output_img_bytearray.seek(0) # Seek to the beginning of the image, otherwise it results in empty datareturn output_img_bytearray
12345671 unmodified line91011121314151628 unmodified lines4546474849505126 unmodified lines7879808182838410 unmodified lines959697989910010116 unmodified lines11811912012112212312412512612714 unmodified lines14214314414514614714814915015115214 unmodified lines1671681691701711721731741751761771781791801811821831841851862 unmodified lines1891901911921931941951 unmodified line1971981992002012022032042052062072082092102112122132142152167 unmodified lines224225226227228229230231232233234235236237238239240import ioimport numpy as npfrom PIL import Image as PIL_Image # gltflibのImageと被るので別名にする。import structimport uuid1 unmodified lineGLTF, GLTFModel, Asset, Scene, Node, Mesh, Primitive, Attributes, Buffer, BufferView, Image, Texture, TextureInfo, Material, Sampler, Accessor, AccessorType,BufferTarget, ComponentType, GLBResource, PBRMetallicRoughness)# 共通バイナリ情報# 頂点データ(POSITION)vertices = [[ 1.0, 1.0, -1.0,],[ 1.0, 1.0, -1.0,],28 unmodified linesmins = [min([vertex[i] for vertex in vertices]) for i in range(3)]maxs = [max([vertex[i] for vertex in vertices]) for i in range(3)]# 法線データ(NORMAL)normals = [[ 0.0, 0.0, -1.0,],[ 0.0, 1.0, -0.0,],26 unmodified linesnormal_bytearray.extend(struct.pack('f', value))normal_bytelen = len(normal_bytearray)# テクスチャ座標(TEXCOORD_0)texcoord_0s = [[0.9, 0.1],[0.9, 0.0],[1.0, 0.1],[0.9, 1.0],[0.9, 0.9],[1.0, 0.9],10 unmodified linestexcoord_0_bytearray.extend(struct.pack('f', value))texcoord_0_bytelen = len(texcoord_0_bytearray)# 頂点インデックスvertex_indices = [1, 14, 20,1, 20, 7,16 unmodified linesdef create_picture_box_model(img_bytearray):# 画像の取得img = PIL_Image.open(img_bytearray).convert('RGB')# 辺の長さが8で割れる数値になるように調整img = img.resize((8 * (img.size[0] // 8), 8 * (img.size[1] // 8)))temp_img = PIL_Image.new('RGB', (int(img.size[0] * 1.25), int(img.size[1] * 1.25)), 'white')temp_img.paste(img, (int(temp_img.size[0] / 10), int(temp_img.size[1] / 10)))14 unmodified linesimg_bytearray = img_bytearray.getvalue()img_bytelen = len(img_bytearray)# 3Dモデルのスケールの計算scale_factor = np.power(img.size[0] * img.size[1], 0.5)scale = (img.size[0] / scale_factor, img.size[1] / scale_factor, 0.1)# バイナリデータ部分の結合bytearray_list = [vertex_bytearray,normal_bytearray,14 unmodified linesall_bytearray = bytearray()for temp_bytearray in bytearray_list:all_bytearray.extend(temp_bytearray)offset_list = [0] + bytelen_cumsum_list # 最初のオフセットは0offset_list.pop() # 末尾を削除# リソースの作成resources = [GLBResource(data=all_bytearray)]# 各種設定# アセットasset=Asset()# バッファbuffers = [Buffer(byteLength=len(all_bytearray))]# バッファビューbufferViews = [BufferView(buffer=0, byteOffset=offset_list[0], byteLength=bytelen_list[0], target=BufferTarget.ARRAY_BUFFER.value),BufferView(buffer=0, byteOffset=offset_list[1], byteLength=bytelen_list[1], target=BufferTarget.ARRAY_BUFFER.value),2 unmodified linesBufferView(buffer=0, byteOffset=offset_list[4], byteLength=bytelen_list[4], target=None),]# アクセサーaccessors = [Accessor(bufferView=0, componentType=ComponentType.FLOAT.value, count=len(vertices), type=AccessorType.VEC3.value, max=maxs, min=mins),Accessor(bufferView=1, componentType=ComponentType.FLOAT.value, count=len(normals), type=AccessorType.VEC3.value, max=None, min=None),1 unmodified lineAccessor(bufferView=3, componentType=ComponentType.UNSIGNED_SHORT.value, count=len(vertex_indices), type=AccessorType.SCALAR.value, max=None, min=None)]# イメージimages=[Image(mimeType='image/jpeg', bufferView=4),]# サンプラーsamplers = [Sampler(magFilter=9728, minFilter=9984)] # magFilter:最近傍フィルタリング、minFilter:ミップマップ+最近傍フィルタリング# テクスチャtextures = [Texture(name='Image',sampler=0,source=0),]# マテリアルmaterials = [Material(pbrMetallicRoughness=PBRMetallicRoughness(7 unmodified lines),]# メッシュmeshes = [Mesh(name='Image', primitives=[Primitive(attributes=Attributes(POSITION=0, NORMAL=1,TEXCOORD_0=2),indices=3, material=0)]),]# ノードnodes = [Node(mesh=0,rotation=None, scale=scale),]# シーンscene = 0scenes = [Scene(name='Scene', nodes=[0])]12345671 unmodified line91011121314151628 unmodified lines4546474849505126 unmodified lines7879808182838410 unmodified lines959697989910010116 unmodified lines11811912012112212312412512612714 unmodified lines14214314414514614714814915015115214 unmodified lines1671681691701711721731741751761771781791801811821831841852 unmodified lines1881891901911921931941 unmodified line1961971981992002012022032042052062072082092102112122132142157 unmodified lines223224225226227228229230231232233234235236237238239import ioimport numpy as npfrom PIL import Image as PIL_Image # Renaming to avoid conflict with Image from gltflibimport structimport uuid1 unmodified lineGLTF, GLTFModel, Asset, Scene, Node, Mesh, Primitive, Attributes, Buffer, BufferView, Image, Texture, TextureInfo, Material, Sampler, Accessor, AccessorType,BufferTarget, ComponentType, GLBResource, PBRMetallicRoughness)# Common Binary Information# Vertex data(POSITION)vertices = [[ 1.0, 1.0, -1.0,],[ 1.0, 1.0, -1.0,],28 unmodified linesmins = [min([vertex[i] for vertex in vertices]) for i in range(3)]maxs = [max([vertex[i] for vertex in vertices]) for i in range(3)]# Normal data(NORMAL)normals = [[ 0.0, 0.0, -1.0,],[ 0.0, 1.0, -0.0,],26 unmodified linesnormal_bytearray.extend(struct.pack('f', value))normal_bytelen = len(normal_bytearray)# Texture coordinates(TEXCOORD_0)texcoord_0s = [[0.9, 0.1],[0.9, 0.0],[1.0, 0.1],[0.9, 1.0],[0.9, 0.9],[1.0, 0.9],10 unmodified linestexcoord_0_bytearray.extend(struct.pack('f', value))texcoord_0_bytelen = len(texcoord_0_bytearray)# Vertex indicesvertex_indices = [1, 14, 20,1, 20, 7,16 unmodified linesdef create_picture_box_model(img_bytearray):# Loading Pictureimg = PIL_Image.open(img_bytearray).convert('RGB')# Adjusting to a Value That Is Divisible by 8 for Edge Lengthimg = img.resize((8 * (img.size[0] // 8), 8 * (img.size[1] // 8)))temp_img = PIL_Image.new('RGB', (int(img.size[0] * 1.25), int(img.size[1] * 1.25)), 'white')temp_img.paste(img, (int(temp_img.size[0] / 10), int(temp_img.size[1] / 10)))14 unmodified linesimg_bytearray = img_bytearray.getvalue()img_bytelen = len(img_bytearray)# Calculating the Scale of a 3D Modelscale_factor = np.power(img.size[0] * img.size[1], 0.5)scale = (img.size[0] / scale_factor, img.size[1] / scale_factor, 0.1)# Concatenation of the binary data sectionbytearray_list = [vertex_bytearray,normal_bytearray,14 unmodified linesall_bytearray = bytearray()for temp_bytearray in bytearray_list:all_bytearray.extend(temp_bytearray)offset_list = [0] + bytelen_cumsum_list # The first offset is 0offset_list.pop() # Remove the end# GLBResourceresources = [GLBResource(data=all_bytearray)]# Assetasset=Asset()# Bufferbuffers = [Buffer(byteLength=len(all_bytearray))]# BufferViewbufferViews = [BufferView(buffer=0, byteOffset=offset_list[0], byteLength=bytelen_list[0], target=BufferTarget.ARRAY_BUFFER.value),BufferView(buffer=0, byteOffset=offset_list[1], byteLength=bytelen_list[1], target=BufferTarget.ARRAY_BUFFER.value),2 unmodified linesBufferView(buffer=0, byteOffset=offset_list[4], byteLength=bytelen_list[4], target=None),]# Accessoraccessors = [Accessor(bufferView=0, componentType=ComponentType.FLOAT.value, count=len(vertices), type=AccessorType.VEC3.value, max=maxs, min=mins),Accessor(bufferView=1, componentType=ComponentType.FLOAT.value, count=len(normals), type=AccessorType.VEC3.value, max=None, min=None),1 unmodified lineAccessor(bufferView=3, componentType=ComponentType.UNSIGNED_SHORT.value, count=len(vertex_indices), type=AccessorType.SCALAR.value, max=None, min=None)]# Imageimages=[Image(mimeType='image/jpeg', bufferView=4),]# Samplersamplers = [Sampler(magFilter=9728, minFilter=9984)] # magFilter:最近傍フィルタリング、minFilter:ミップマップ+最近傍フィルタリング# Texturetextures = [Texture(name='Image',sampler=0,source=0),]# Materialmaterials = [Material(pbrMetallicRoughness=PBRMetallicRoughness(7 unmodified lines),]# Meshmeshes = [Mesh(name='Image', primitives=[Primitive(attributes=Attributes(POSITION=0, NORMAL=1,TEXCOORD_0=2),indices=3, material=0)]),]# Nodenodes = [Node(mesh=0,rotation=None, scale=scale),]# Scenescene = 0scenes = [Scene(name='Scene', nodes=[0])]
app.py+8-9
src/card_model.py+37-37
src/extracted_objects_model.py+40-40
src/front_card_image.py+18-18
src/front_card_image_historic_site.py+29-29
src/picture_box_model.py+24-25