Spaces:
Paused
Paused
Commit ·
fd51374
1
Parent(s): 5f29e78
add: 9:16 layouts
Browse files78 unmodified lines79808182838485298 unmodified lines3843853863873883893903911 unmodified line39339439539639739839976 unmodified lines4764774784794804814824836 unmodified lines4904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445451 unmodified line5475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006017 unmodified lines6096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696702 unmodified lines67367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283313 unmodified lines8478488498508518528538548558568578588598608613 unmodified lines8658668678688698708712 unmodified lines87487587687787887943 unmodified lines9239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539542 unmodified lines95795895996096196296396496596696796896997097197297397497597697778 unmodified linesinput_image,num_divisions=20,margin=90,font_size=120,dot_spacing=20,):"""298 unmodified linesdef create_layouts(image, left_division, right_division):"""Create different layout variations of the image using half, one-third, and two-thirds width.All layout variations will be centered on detected persons, including 16:9 and 9:16 crops.Args:image: PIL Image1 unmodified lineright_division: Right division index (1-20)Returns:tuple: (list of layout variations, cutout_image, cutout_16_9, cutout_9_16)"""# Convert PIL Image to cv2 formatif isinstance(image, Image.Image):76 unmodified linesx_end = min(cutout_width, x_start + new_width)cutout_16_9 = cutout_image[:, x_start:x_end].copy()# For 9:16 version (centered on person)target_width_9_16 = int(cutout_height * aspect_9_16)if target_width_9_16 <= cutout_width:# Center horizontally around personx_start = int(6 unmodified lines))x_end = int(min(cutout_width, x_start + target_width_9_16))cutout_9_16 = cutout_image[:, x_start:x_end].copy()else:# Handle rare case where we need to adjust heightnew_height = int(cutout_width / aspect_9_16)y_start = int(max(0, min(cutout_height - new_height, cutout_center_y - new_height // 2)))y_end = int(min(cutout_height, y_start + new_height))cutout_9_16 = cutout_image[y_start:y_end, :].copy()# 4. Scale the center back to original image coordinatesoriginal_center_x = left_boundary + cutout_center_x# 5. Create layout variations on the original image centered on persons# Half width layouthalf_width = width // 2half_left_x = max(0, min(width - half_width, original_center_x - half_width // 2))half_right_x = half_left_x + half_widthhalf_width_crop = image_cv[:, half_left_x:half_right_x].copy()# Third width layoutthird_width = width // 3third_left_x = max(0, min(width - third_width, original_center_x - third_width // 2))third_right_x = third_left_x + third_widththird_width_crop = image_cv[:, third_left_x:third_right_x].copy()# Two-thirds width layouttwo_thirds_width = (width * 2) // 3two_thirds_left_x = max(0, min(width - two_thirds_width, original_center_x - two_thirds_width // 2))two_thirds_right_x = two_thirds_left_x + two_thirds_widthtwo_thirds_crop = image_cv[:, two_thirds_left_x:two_thirds_right_x].copy()# Add labels to all cropsfont = cv2.FONT_HERSHEY_SIMPLEXlabel_settings = {"fontScale": 1.0,"fontFace": 1,"thickness": 2,}# Draw label backgrounds for better visibilitydef add_label(img, label):# Draw background for texttext_size = cv2.getTextSize(label, **{k: v for k, v in label_settings.items() if k != "color"})cv2.rectangle(img,(10, 10),1 unmodified line(0, 0, 0),-1,) # Black background# Draw textcv2.putText(img,label,(15, 15 + text_size[0][1]),**label_settings,color=(255, 255, 255),lineType=cv2.LINE_AA,)return imgcutout_image = add_label(cutout_image, "Cutout")cutout_16_9 = add_label(cutout_16_9, "16:9")cutout_9_16 = add_label(cutout_9_16, "9:16")half_width_crop = add_label(half_width_crop, "Half Width")third_width_crop = add_label(third_width_crop, "Third Width")two_thirds_crop = add_label(two_thirds_crop, "Two-Thirds Width")# Convert all output images to PIL formatlayout_crops = []for layout, label in [(half_width_crop, "Half Width"),(third_width_crop, "Third Width"),(two_thirds_crop, "Two-Thirds Width"),]:pil_layout = Image.fromarray(cv2.cvtColor(layout, cv2.COLOR_BGR2RGB))layout_crops.append(pil_layout)cutout_pil = Image.fromarray(cv2.cvtColor(cutout_image, cv2.COLOR_BGR2RGB))cutout_16_9_pil = Image.fromarray(cv2.cvtColor(cutout_16_9, cv2.COLOR_BGR2RGB))cutout_9_16_pil = Image.fromarray(cv2.cvtColor(cutout_9_16, cv2.COLOR_BGR2RGB))return layout_crops, cutout_pil, cutout_16_9_pil, cutout_9_16_pildef draw_crops_on_original(image, left_division, right_division, crop_types):"""Create a visualization showing selected crop regions overlaid on the original image.Each crop region is outlined with a different color and labeled.All crops are centered on the person's center point.Args:image: PIL Imageleft_division: Left division index (1-20)right_division: Right division index (1-20)crop_types: List of crop types to include in visualization (e.g., ["16:9", "9:16"])Returns:PIL Image: Original image with selected crop regions visualized"""# Convert PIL Image to cv2 formatif isinstance(image, Image.Image):7 unmodified lines# Get image dimensionsheight, width = image_cv.shape[:2]# Calculate division width and crop boundariesdivision_width = width / 20 # Assuming 20 divisionsleft_boundary = int((left_division - 1) * division_width)right_boundary = int(right_division * division_width)# Find person bounding box and center in cutoutcutout_image = image_cv[:, left_boundary:right_boundary].copy()# Get YOLO detections for person bounding boxresults = model(cutout_image, classes=[0], conf=0.6)# Default valuescutout_center_x = cutout_image.shape[1] // 2cutout_center_y = cutout_image.shape[0] // 2person_top = 0.0person_height = float(cutout_image.shape[0])if results and len(results[0].boxes) > 0:# Get person detectionboxes = results[0].boxes.xyxy.cpu().numpy()if len(boxes) == 1:# Single personx1, y1, x2, y2 = boxes[0]cutout_center_x = int((x1 + x2) // 2)cutout_center_y = int((y1 + y2) // 2)person_top = y1person_height = y2 - y1else:# Multiple persons - merge bounding boxesleft_x = min(box[0] for box in boxes)right_x = max(box[2] for box in boxes)top_y = min(box[1] for box in boxes) # Top of highest personbottom_y = max(box[3] for box in boxes) # Bottom of lowest personcutout_center_x = int((left_x + right_x) // 2)cutout_center_y = int((top_y + bottom_y) // 2)person_top = top_yperson_height = bottom_y - top_y# Scale back to original imageoriginal_center_x = left_boundary + cutout_center_xoriginal_center_y = cutout_center_yoriginal_person_top = (person_top # Already in original image space since we didn't crop vertically)original_person_height = person_height # Same in original space# Define colors for different crops (BGR format)colors = {"cutout": (0, 165, 255), # Orange"16:9": (0, 255, 0), # Green"9:16": (255, 0, 0), # Blue"half": (255, 255, 0), # Cyan"third": (255, 0, 255), # Magenta"two_thirds": (0, 255, 255), # Yellow}# Define line thickness and font2 unmodified linesfont_scale = 0.8font_thickness = 2# Draw cutout region (original divisions) if requestedif "cutout" in crop_types:cv2.rectangle(visualization,(left_boundary, 0),(right_boundary, height),colors["cutout"],thickness,)cv2.putText(visualization,"Cutout",(left_boundary + 5, 30),font,font_scale,colors["cutout"],font_thickness,)# Create 16:9 version of the cutout if requestedif "16:9" in crop_types:cutout_width = right_boundary - left_boundarycutout_height = heightaspect_16_9 = 16 / 9target_height_16_9 = int(cutout_width / aspect_16_9)if target_height_16_9 <= height:# Calculate 20% of person height for top margintop_margin = int(original_person_height * 0.2)# Start 20% above the person's topy_start = int(max(0, original_person_top - top_margin))# If this would make the crop exceed the bottom, adjust y_startif y_start + target_height_16_9 > height:y_start = int(max(0, height - target_height_16_9))y_end = int(min(height, y_start + target_height_16_9))cv2.rectangle(visualization,(left_boundary, y_start),(right_boundary, y_end),colors["16:9"],thickness,)cv2.putText(visualization,"16:9",(left_boundary + 5, y_start + 30),font,font_scale,colors["16:9"],font_thickness,)# Create 9:16 version if requestedif "9:16" in crop_types:cutout_width = right_boundary - left_boundarycutout_height = heightaspect_9_16 = 9 / 16target_width_9_16 = int(cutout_height * aspect_9_16)if target_width_9_16 <= cutout_width:# Center horizontally around personx_start = max(0,min(left_boundary + cutout_width - target_width_9_16,original_center_x - target_width_9_16 // 2,),)x_end = x_start + target_width_9_16cv2.rectangle(visualization, (x_start, 0), (x_end, height), colors["9:16"], thickness)cv2.putText(visualization,"9:16",(x_start + 5, 60),font,font_scale,colors["9:16"],font_thickness,)# Draw centered half width layout if requestedif "half" in crop_types:half_width = width // 2half_left_x = max(0, min(width - half_width, original_center_x - half_width // 2))half_right_x = half_left_x + half_widthcv2.rectangle(visualization,(half_left_x, 0),(half_right_x, height),colors["half"],thickness,)cv2.putText(visualization,"Half Width",(half_left_x + 5, 90),font,font_scale,colors["half"],font_thickness,)# Draw centered third width layout if requestedif "third" in crop_types:third_width = width // 3third_left_x = max(0, min(width - third_width, original_center_x - third_width // 2))third_right_x = third_left_x + third_widthcv2.rectangle(visualization,(third_left_x, 0),(third_right_x, height),colors["third"],thickness,)cv2.putText(visualization,"Third Width",(third_left_x + 5, 120),font,font_scale,colors["third"],font_thickness,)# Draw centered two-thirds width layout if requestedif "two_thirds" in crop_types:two_thirds_width = (width * 2) // 3two_thirds_left_x = max(0, min(width - two_thirds_width, original_center_x - two_thirds_width // 2))two_thirds_right_x = two_thirds_left_x + two_thirds_widthcv2.rectangle(visualization,(two_thirds_left_x, 0),(two_thirds_right_x, height),colors["two_thirds"],thickness,)cv2.putText(visualization,"Two-Thirds Width",(two_thirds_left_x + 5, 150),font,font_scale,colors["two_thirds"],font_thickness,)13 unmodified lines(0, 0, 0),2,)cv2.putText(visualization,"Person Center",(original_center_x + 10, original_center_y),font,font_scale,(255, 255, 255),font_thickness,)# Convert back to PIL formatvisualization_pil = Image.fromarray(cv2.cvtColor(visualization, cv2.COLOR_BGR2RGB))3 unmodified linesdef get_image_crop(cid=None, rsid=None, uid=None):"""Function that returns both 16:9 and 9:16 crops and layout variations for visualization.Returns:gr.Gallery: Gallery of all generated images2 unmodified linesimage_paths = get_sprite_firebase(cid, rsid, uid)except Exception:image_paths = ["data/sprite1.jpg", "data/sprite2.jpg"]# Lists to store all imagesall_images = []all_captions = []43 unmodified linesprint(f"Using divisions: left={left_division}, right={right_division}")# Create layouts and cutoutslayouts, cutout_image, cutout_16_9, cutout_9_16 = create_layouts(mid_image, left_division, right_division)# Create the first visualization with 16:9 and 9:16 crops onlyaspect_ratio_visualization = draw_crops_on_original(mid_image, left_division, right_division, ["16:9", "9:16"])# Create the second visualization with the remaining layoutsother_layouts_visualization = draw_crops_on_original(mid_image,left_division,right_division,["cutout", "half", "third", "two_thirds"],)# Add visualizations showing cropsall_images.append(aspect_ratio_visualization)all_captions.append(f"Aspect Ratio Crops (16:9 & 9:16) {aspect_ratio_visualization.size}")all_images.append(other_layouts_visualization)all_captions.append(f"Other Layout Options {other_layouts_visualization.size}")# Add input and middle image to galleryall_images.append(input_image)2 unmodified linesall_images.append(mid_image)all_captions.append(f"Middle Thumbnail {mid_image.size}")# Add cutout images to galleryall_images.append(cutout_image)all_captions.append(f"Cutout Image {cutout_image.size}")all_images.append(cutout_16_9)all_captions.append(f"16:9 Crop {cutout_16_9.size}")all_images.append(cutout_9_16)all_captions.append(f"9:16 Crop {cutout_9_16.size}")# Add layout variationsfor i, layout in enumerate(layouts):label = ["Half Width", "Third Width", "Two-Thirds Width"][i]all_images.append(layout)all_captions.append(f"{label} {layout.size}")# Return gallery with all imagesreturn gr.Gallery(value=list(zip(all_images, all_captions)))78 unmodified lines79808182838485298 unmodified lines3843853863873883893903911 unmodified line39339439539639739839976 unmodified lines4764774784794804814824834844854864876 unmodified lines4944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559561 unmodified line9589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410657 unmodified lines1073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111022 unmodified lines110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155813 unmodified lines1572157315741575157615773 unmodified lines15811582158315841585158615872 unmodified lines159015911592159315941595159643 unmodified lines16401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817092 unmodified lines171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173678 unmodified linesinput_image,num_divisions=20,margin=90,font_size=70,dot_spacing=20,):"""298 unmodified linesdef create_layouts(image, left_division, right_division):"""Create different layout variations of the image using specific aspect ratios.All layout variations will be centered on detected persons.Args:image: PIL Image1 unmodified lineright_division: Right division index (1-20)Returns:tuple: (standard_crops, threehalfs_layouts, twothirdhalfs_layouts, twoequalhalfs_layouts, visualization_data)"""# Convert PIL Image to cv2 formatif isinstance(image, Image.Image):76 unmodified linesx_end = min(cutout_width, x_start + new_width)cutout_16_9 = cutout_image[:, x_start:x_end].copy()# For 9:16 version (centered on person, adjusted upward for face visibility)target_width_9_16 = int(cutout_height * aspect_9_16)# Adjust center point upward by 20% of person height to ensure face is visibleadjusted_center_y = int(cutout_center_y - (person_height * 0.2))if target_width_9_16 <= cutout_width:# Center horizontally around personx_start = int(6 unmodified lines))x_end = int(min(cutout_width, x_start + target_width_9_16))# Use adjusted center point for vertical positioningy_start = int(max(0,min(cutout_height - cutout_height,adjusted_center_y - cutout_height // 2,),))cutout_9_16 = cutout_image[y_start:, x_start:x_end].copy()else:# Handle rare case where we need to adjust heightnew_height = int(cutout_width / aspect_9_16)# Use adjusted center point for vertical positioningy_start = int(max(0, min(cutout_height - new_height, adjusted_center_y - new_height // 2)))y_end = int(min(cutout_height, y_start + new_height))cutout_9_16 = cutout_image[y_start:y_end, :].copy()# 4. Scale the center back to original image coordinatesoriginal_center_x = left_boundary + cutout_center_xoriginal_center_y = cutout_center_yoriginal_person_top = person_top# Store visualization data for drawingvisualization_data = {"original_center_x": original_center_x,"original_center_y": original_center_y,"original_person_top": original_person_top,"original_person_height": person_height,"cutout_bounds": (left_boundary, right_boundary),}# 5. Create new layout variations - each segment is independently centered on the subject# ----- Create crops for threehalfs layout -----# For 16:9 (three 5.3:9 segments, each independently centered)aspect_5_3_9 = 5.3 / 9# Calculate dimensions for each segmentsegment_height_16_9 = cutout_height # Use full heightsegment_width_16_9 = int(segment_height_16_9 * aspect_5_3_9)# Create three segments for 16:9 threehalfs - all centered on the personthreehalfs_16_9_segments = []for i in range(3):# Each segment is centered on the personsegment_x_start = int(max(0,min(cutout_width - segment_width_16_9,cutout_center_x - segment_width_16_9 // 2,),))segment_x_end = int(min(cutout_width, segment_x_start + segment_width_16_9))# Create the segmentsegment = cutout_image[:, segment_x_start:segment_x_end].copy()# Add a label for visualizationlabel = f"Part {i+1}"cv2.putText(segment,label,(10, 30),cv2.FONT_HERSHEY_SIMPLEX,0.8,(255, 255, 255),2,cv2.LINE_AA,)threehalfs_16_9_segments.append(segment)# For 9:16 (three 9:5.3 segments, each independently centered)aspect_9_5_3 = 9 / 5.3# Calculate dimensions for each segmentsegment_width_9_16 = cutout_9_16.shape[1] # Use full width of 9:16 cropsegment_height_9_16 = int(segment_width_9_16 / aspect_9_5_3)# Get adjusted center for 9:16 segments (move up by 20% of person height)cutout_9_16_center_y = cutout_9_16.shape[0] // 2adjusted_9_16_center_y = int(cutout_9_16_center_y - (person_height * 0.2))cutout_9_16_height = cutout_9_16.shape[0]# Create three segments for 9:16 threehalfs - all centered on the personthreehalfs_9_16_segments = []for i in range(3):# Each segment is centered on the person with adjusted center pointsegment_y_start = int(max(0,min(cutout_9_16_height - segment_height_9_16,adjusted_9_16_center_y - segment_height_9_16 // 2,),))segment_y_end = int(min(cutout_9_16_height, segment_y_start + segment_height_9_16))# Create the segmentsegment = cutout_9_16[segment_y_start:segment_y_end, :].copy()# Add a label for visualizationlabel = f"Part {i+1}"cv2.putText(segment,label,(10, 30),cv2.FONT_HERSHEY_SIMPLEX,0.8,(255, 255, 255),2,cv2.LINE_AA,)threehalfs_9_16_segments.append(segment)# ----- Create crops for twothirdhalfs layout -----# For 16:9 (two segments: 10.6:9 and 5.3:9 OR 5.3:9 and 10.6:9)aspect_10_6_9 = 10.6 / 9# Calculate dimensions for segmentssegment1_height_16_9 = cutout_height # Use full heightsegment1_width_16_9 = int(segment1_height_16_9 * aspect_10_6_9)segment2_height_16_9 = cutout_height # Use full heightsegment2_width_16_9 = int(segment2_height_16_9 * aspect_5_3_9)# Create segments for 16:9 twothirdhalfs var1 (10.6:9 then 5.3:9)# Both segments independently centered on the person# First segment (10.6:9)segment_x_start = int(max(0,min(cutout_width - segment1_width_16_9,cutout_center_x - segment1_width_16_9 // 2,),))segment_x_end = int(min(cutout_width, segment_x_start + segment1_width_16_9))segment1 = cutout_image[:, segment_x_start:segment_x_end].copy()# Add labelcv2.putText(segment1,"10.6:9",(10, 30),cv2.FONT_HERSHEY_SIMPLEX,0.8,(255, 255, 255),2,cv2.LINE_AA,)# Second segment (5.3:9)segment_x_start = int(max(0,min(cutout_width - segment2_width_16_9,cutout_center_x - segment2_width_16_9 // 2,),))segment_x_end = int(min(cutout_width, segment_x_start + segment2_width_16_9))segment2 = cutout_image[:, segment_x_start:segment_x_end].copy()# Add labelcv2.putText(segment2,"5.3:9",(10, 30),cv2.FONT_HERSHEY_SIMPLEX,0.8,(255, 255, 255),2,cv2.LINE_AA,)twothirdhalfs_16_9_var1_segments = [segment1, segment2]# Create segments for 16:9 twothirdhalfs var2 (5.3:9 then 10.6:9)# First segment (5.3:9) - reuse segment2 from var1# Second segment (10.6:9) - reuse segment1 from var1twothirdhalfs_16_9_var2_segments = [segment2.copy(), segment1.copy()]# For 9:16 (two segments stacked: 9:10.6 and 9:5.3 OR 9:5.3 and 9:10.6)aspect_9_10_6 = 9 / 10.6aspect_9_5_3 = 9 / 5.3# Calculate dimensions for segmentssegment1_width_9_16 = cutout_9_16.shape[1] # Use full width of 9:16 cropsegment1_height_9_16 = int(segment1_width_9_16 / aspect_9_10_6)segment2_width_9_16 = cutout_9_16.shape[1] # Use full width of 9:16 cropsegment2_height_9_16 = int(segment2_width_9_16 / aspect_9_5_3)# Create segments for 9:16 twothirdhalfs var1 (9:10.6 then 9:5.3)# Both segments independently centered on the person with adjusted center point# First segment (9:10.6)segment_y_start = int(max(0,min(cutout_9_16_height - segment1_height_9_16,adjusted_9_16_center_y - segment1_height_9_16 // 2,),))segment_y_end = int(min(cutout_9_16_height, segment_y_start + segment1_height_9_16))segment1 = cutout_9_16[segment_y_start:segment_y_end, :].copy()# Add labelcv2.putText(segment1,"9:10.6",(10, 30),cv2.FONT_HERSHEY_SIMPLEX,0.8,(255, 255, 255),2,cv2.LINE_AA,)# Second segment (9:5.3)segment_y_start = int(max(0,min(cutout_9_16_height - segment2_height_9_16,adjusted_9_16_center_y - segment2_height_9_16 // 2,),))segment_y_end = int(min(cutout_9_16_height, segment_y_start + segment2_height_9_16))segment2 = cutout_9_16[segment_y_start:segment_y_end, :].copy()# Add labelcv2.putText(segment2,"9:5.3",(10, 30),cv2.FONT_HERSHEY_SIMPLEX,0.8,(255, 255, 255),2,cv2.LINE_AA,)twothirdhalfs_9_16_var1_segments = [segment1, segment2]# Create segments for 9:16 twothirdhalfs var2 (9:5.3 then 9:10.6)# First segment (9:5.3) - reuse segment2 from var1# Second segment (9:10.6) - reuse segment1 from var1twothirdhalfs_9_16_var2_segments = [segment2.copy(), segment1.copy()]# ----- Create crops for twoequalhalfs layout -----# For 16:9 (two 8:9 segments side by side)aspect_8_9 = 8 / 9# Calculate dimensions for segmentssegment_height_16_9_equal = cutout_height # Use full heightsegment_width_16_9_equal = int(segment_height_16_9_equal * aspect_8_9)# Create segments for 16:9 twoequalhalfs - both centered on the person# First segment (8:9)segment_x_start = int(max(0,min(cutout_width - segment_width_16_9_equal,cutout_center_x - segment_width_16_9_equal // 2,),))segment_x_end = int(min(cutout_width, segment_x_start + segment_width_16_9_equal))segment1 = cutout_image[:, segment_x_start:segment_x_end].copy()# Add labelcv2.putText(segment1,"8:9 (1)",(10, 30),cv2.FONT_HERSHEY_SIMPLEX,0.8,(255, 255, 255),2,cv2.LINE_AA,)# Second segment (identical to first for equal halfs)segment2 = segment1.copy()# Update label for segment 2cv2.putText(segment2,"8:9 (2)",(10, 30),cv2.FONT_HERSHEY_SIMPLEX,0.8,(255, 255, 255),2,cv2.LINE_AA,)twoequalhalfs_16_9_segments = [segment1, segment2]# For 9:16 (two 9:8 segments stacked)aspect_9_8 = 9 / 8# Calculate dimensions for segmentssegment_width_9_16_equal = cutout_9_16.shape[1] # Use full width of 9:16 cropsegment_height_9_16_equal = int(segment_width_9_16_equal / aspect_9_8)# Create segments for 9:16 twoequalhalfs - both centered on the person with adjusted center point# First segment (9:8)segment_y_start = int(max(0,min(cutout_9_16_height - segment_height_9_16_equal,adjusted_9_16_center_y - segment_height_9_16_equal // 2,),))segment_y_end = int(min(cutout_9_16_height, segment_y_start + segment_height_9_16_equal))segment1 = cutout_9_16[segment_y_start:segment_y_end, :].copy()# Add labelcv2.putText(segment1,"9:8 (1)",(10, 30),cv2.FONT_HERSHEY_SIMPLEX,0.8,(255, 255, 255),2,cv2.LINE_AA,)# Second segment (identical to first for equal halfs)segment2 = segment1.copy()# Update label for segment 2cv2.putText(segment2,"9:8 (2)",(10, 30),cv2.FONT_HERSHEY_SIMPLEX,0.8,(255, 255, 255),2,cv2.LINE_AA,)twoequalhalfs_9_16_segments = [segment1, segment2]# 6. Create composite layouts by joining segments# Function to create a composite imagedef create_composite(segments, horizontal=True):if not segments:return Noneif horizontal:# Calculate the total width and max heighttotal_width = sum(segment.shape[1] for segment in segments)max_height = max(segment.shape[0] for segment in segments)# Create a canvascomposite = np.zeros((max_height, total_width, 3), dtype=np.uint8)# Place segments side by sidex_offset = 0for segment in segments:h, w = segment.shape[:2]composite[:h, x_offset : x_offset + w] = segmentx_offset += welse: # vertical stacking# Calculate the max width and total heightmax_width = max(segment.shape[1] for segment in segments)total_height = sum(segment.shape[0] for segment in segments)# Create a canvascomposite = np.zeros((total_height, max_width, 3), dtype=np.uint8)# Place segments top to bottomy_offset = 0for segment in segments:h, w = segment.shape[:2]composite[y_offset : y_offset + h, :w] = segmenty_offset += hreturn composite# Create composite layoutsthreehalfs_16_9_composite = create_composite(threehalfs_16_9_segments, horizontal=True)threehalfs_9_16_composite = create_composite(threehalfs_9_16_segments, horizontal=False)twothirdhalfs_16_9_var1_composite = create_composite(twothirdhalfs_16_9_var1_segments, horizontal=True)twothirdhalfs_16_9_var2_composite = create_composite(twothirdhalfs_16_9_var2_segments, horizontal=True)twothirdhalfs_9_16_var1_composite = create_composite(twothirdhalfs_9_16_var1_segments, horizontal=False)twothirdhalfs_9_16_var2_composite = create_composite(twothirdhalfs_9_16_var2_segments, horizontal=False)twoequalhalfs_16_9_composite = create_composite(twoequalhalfs_16_9_segments, horizontal=True)twoequalhalfs_9_16_composite = create_composite(twoequalhalfs_9_16_segments, horizontal=False)# Add labels to all compositesdef add_label(img, label):if img is None:return Nonefont = cv2.FONT_HERSHEY_SIMPLEXlabel_settings = {"fontScale": 1.0,"fontFace": font,"thickness": 2,}# Draw background for texttext_size = cv2.getTextSize(label,fontFace=label_settings["fontFace"],fontScale=label_settings["fontScale"],thickness=label_settings["thickness"],)cv2.rectangle(img,(10, 10),1 unmodified line(0, 0, 0),-1,) # Black background# Draw textcv2.putText(img,label,(15, 15 + text_size[0][1]),fontFace=label_settings["fontFace"],fontScale=label_settings["fontScale"],thickness=label_settings["thickness"],color=(255, 255, 255),lineType=cv2.LINE_AA,)return img# Label the basic cropscutout_image_labeled = add_label(cutout_image.copy(), "Cutout")cutout_16_9_labeled = add_label(cutout_16_9.copy(), "16:9")cutout_9_16_labeled = add_label(cutout_9_16.copy(), "9:16")# Label the composite layoutsthreehalfs_16_9_labeled = add_label(threehalfs_16_9_composite, "Three Halfs 16:9")threehalfs_9_16_labeled = add_label(threehalfs_9_16_composite, "Three Halfs 9:16")twothirdhalfs_16_9_var1_labeled = add_label(twothirdhalfs_16_9_var1_composite, "Two Thirds Var1 16:9")twothirdhalfs_16_9_var2_labeled = add_label(twothirdhalfs_16_9_var2_composite, "Two Thirds Var2 16:9")twothirdhalfs_9_16_var1_labeled = add_label(twothirdhalfs_9_16_var1_composite, "Two Thirds Var1 9:16")twothirdhalfs_9_16_var2_labeled = add_label(twothirdhalfs_9_16_var2_composite, "Two Thirds Var2 9:16")twoequalhalfs_16_9_labeled = add_label(twoequalhalfs_16_9_composite, "Two Equal Halfs 16:9")twoequalhalfs_9_16_labeled = add_label(twoequalhalfs_9_16_composite, "Two Equal Halfs 9:16")# Convert all output images to PIL formatdef cv2_to_pil(img):if img is None:return Nonereturn Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))# Convert standard cropsstandard_crops = {"cutout": cv2_to_pil(cutout_image_labeled),"16:9": cv2_to_pil(cutout_16_9_labeled),"9:16": cv2_to_pil(cutout_9_16_labeled),}# Convert threehalfs layoutsthreehalfs_layouts = {"16:9": cv2_to_pil(threehalfs_16_9_labeled),"9:16": cv2_to_pil(threehalfs_9_16_labeled),}# Convert twothirdhalfs layoutstwothirdhalfs_layouts = {"16:9_var1": cv2_to_pil(twothirdhalfs_16_9_var1_labeled),"16:9_var2": cv2_to_pil(twothirdhalfs_16_9_var2_labeled),"9:16_var1": cv2_to_pil(twothirdhalfs_9_16_var1_labeled),"9:16_var2": cv2_to_pil(twothirdhalfs_9_16_var2_labeled),}# Convert twoequalhalfs layoutstwoequalhalfs_layouts = {"16:9": cv2_to_pil(twoequalhalfs_16_9_labeled),"9:16": cv2_to_pil(twoequalhalfs_9_16_labeled),}return (standard_crops,threehalfs_layouts,twothirdhalfs_layouts,twoequalhalfs_layouts,visualization_data,)def draw_layout_regions(image, left_division, right_division, visualization_data, layout_type):"""Create a visualization showing the layout regions overlaid on the original image.Each region is independently centered on the subject, as in practice different videoswould be stacked in these layouts.Args:image: PIL Imageleft_division: Left division index (1-20)right_division: Right division index (1-20)visualization_data: Dictionary with visualization data from create_layoutslayout_type: Type of layout to visualize (e.g., "standard", "threehalfs", "twothirdhalfs_var1", etc.)Returns:PIL Image: Original image with layout regions visualized"""# Convert PIL Image to cv2 formatif isinstance(image, Image.Image):7 unmodified lines# Get image dimensionsheight, width = image_cv.shape[:2]# Extract visualization dataoriginal_center_x = visualization_data["original_center_x"]original_center_y = visualization_data["original_center_y"]original_person_top = visualization_data["original_person_top"]original_person_height = visualization_data["original_person_height"]left_boundary, right_boundary = visualization_data["cutout_bounds"]cutout_width = right_boundary - left_boundary# Define colors for different layouts (BGR format)colors = {"standard": {"16:9": (0, 255, 0), "9:16": (255, 0, 0)}, # Green, Blue"threehalfs": {"16:9": (0, 165, 255), "9:16": (255, 255, 0)}, # Orange, Cyan"twothirdhalfs_var1": {"16:9": (255, 0, 255),"9:16": (128, 0, 128),}, # Magenta, Purple"twothirdhalfs_var2": {"16:9": (0, 255, 255),"9:16": (128, 128, 0),}, # Yellow, Teal"twoequalhalfs": {"16:9": (0, 128, 128),"9:16": (255, 165, 0),}, # Dark Cyan, Blue-Green}# Define line thickness and font2 unmodified linesfont_scale = 0.8font_thickness = 2# Draw standard layouts (16:9 and 9:16)if layout_type == "standard":# Draw 16:9 cropaspect_16_9 = 16 / 9target_height_16_9 = int(cutout_width / aspect_16_9)# Calculate 20% of person height for top margintop_margin = int(original_person_height * 0.2)y_start = int(max(0, original_person_top - top_margin))if y_start + target_height_16_9 > height:y_start = int(max(0, height - target_height_16_9))y_end = int(min(height, y_start + target_height_16_9))cv2.rectangle(visualization,(left_boundary, y_start),(right_boundary, y_end),colors["standard"]["16:9"],thickness,)cv2.putText(visualization,"16:9",(left_boundary + 5, y_start + 30),font,font_scale,colors["standard"]["16:9"],font_thickness,)# Draw 9:16 cropaspect_9_16 = 9 / 16target_width_9_16 = int(height * aspect_9_16)x_start = max(0,min(width - target_width_9_16, original_center_x - target_width_9_16 // 2),)x_end = x_start + target_width_9_16cv2.rectangle(visualization,(x_start, 0),(x_end, height),colors["standard"]["9:16"],thickness,)cv2.putText(visualization,"9:16",(x_start + 5, 30),font,font_scale,colors["standard"]["9:16"],font_thickness,)# Draw threehalfs layouts - each segment is centered on the subjectelif layout_type == "threehalfs":# For 16:9 (three 5.3:9 segments side by side - visually only)aspect_5_3_9 = 5.3 / 9segment_height = heightsegment_width = int(segment_height * aspect_5_3_9)# Calculate total width for visualization purposestotal_width = segment_width * 3start_x = max(0, original_center_x - total_width // 2)for i in range(3):# For visualization, we'll place them side by sidevis_segment_x_start = start_x + i * segment_widthvis_segment_x_end = vis_segment_x_start + segment_width# But each segment would actually be centered on the subject independently# Here we also draw the centered version more faintlyactual_segment_x_start = max(0, min(width - segment_width, original_center_x - segment_width // 2))actual_segment_x_end = min(width, actual_segment_x_start + segment_width)# Draw the visualization placement (side by side)cv2.rectangle(visualization,(vis_segment_x_start, 0),(vis_segment_x_end, segment_height),colors["threehalfs"]["16:9"],thickness,)# Draw the actual centered placement with dashed linesif i > 0: # Only draw centered versions for parts 2 and 3for j in range(0, segment_height, 20): # Dashed line effectif j % 40 < 20: # Skip every other segmentcv2.line(visualization,(actual_segment_x_start, j),(actual_segment_x_start, min(j + 20, segment_height)),colors["threehalfs"]["16:9"],1,)cv2.line(visualization,(actual_segment_x_end, j),(actual_segment_x_end, min(j + 20, segment_height)),colors["threehalfs"]["16:9"],1,)cv2.putText(visualization,f"16:9 Part {i+1}",(vis_segment_x_start + 5, 30 + i * 30),font,font_scale,colors["threehalfs"]["16:9"],font_thickness,)# For 9:16 (three 9:5.3 segments stacked top to bottom - visually only)aspect_9_16 = 9 / 16target_width_9_16 = int(height * aspect_9_16)x_start = max(0,min(width - target_width_9_16, original_center_x - target_width_9_16 // 2),)x_end = x_start + target_width_9_16aspect_9_5_3 = 9 / 5.3segment_width_9_16 = target_width_9_16segment_height_9_16 = int(segment_width_9_16 / aspect_9_5_3)# Calculate total height for visualization purposestotal_height = segment_height_9_16 * 3start_y = max(0, height // 2 - total_height // 2)for i in range(3):# For visualization, we'll place them stackedvis_segment_y_start = start_y + i * segment_height_9_16vis_segment_y_end = min(height, vis_segment_y_start + segment_height_9_16)# But each segment would actually be centered on the subject independently# Here we also draw the centered version more faintlyactual_segment_y_start = max(0,min(height - segment_height_9_16,original_center_y - segment_height_9_16 // 2,),)actual_segment_y_end = min(height, actual_segment_y_start + segment_height_9_16)# Draw the visualization placement (stacked)cv2.rectangle(visualization,(x_start, vis_segment_y_start),(x_end, vis_segment_y_end),colors["threehalfs"]["9:16"],thickness,)# Draw the actual centered placement with dashed linesif i > 0: # Only draw centered versions for parts 2 and 3for j in range(x_start, x_end, 20): # Dashed line effectif j % 40 < 20: # Skip every other segmentcv2.line(visualization,(j, actual_segment_y_start),(min(j + 20, x_end), actual_segment_y_start),colors["threehalfs"]["9:16"],1,)cv2.line(visualization,(j, actual_segment_y_end),(min(j + 20, x_end), actual_segment_y_end),colors["threehalfs"]["9:16"],1,)cv2.putText(visualization,f"9:16 Part {i+1}",(x_start + 5, vis_segment_y_start + 30),font,font_scale,colors["threehalfs"]["9:16"],font_thickness,)# Draw twothirdhalfs layoutselif layout_type == "twothirdhalfs_var1" or layout_type == "twothirdhalfs_var2":aspect_key = "16:9" if layout_type.endswith("var1") else "9:16"layout_color = colors[("twothirdhalfs_var1"if layout_type.endswith("var1")else "twothirdhalfs_var2")][aspect_key]if aspect_key == "16:9":# For 16:9 (two segments side by side)aspect_10_6_9 = 10.6 / 9aspect_5_3_9 = 5.3 / 9segment1_height = heightsegment1_width = int(segment1_height* (aspect_10_6_9 if layout_type.endswith("var1") else aspect_5_3_9))segment2_height = heightsegment2_width = int(segment2_height* (aspect_5_3_9 if layout_type.endswith("var1") else aspect_10_6_9))# First segmentsegment_center_x = original_center_x - segment2_width // 4segment_x_start = int(max(0,min(width - segment1_width, segment_center_x - segment1_width // 2),))segment_x_end = int(min(width, segment_x_start + segment1_width))cv2.rectangle(visualization,(segment_x_start, 0),(segment_x_end, segment1_height),layout_color,thickness,)cv2.putText(visualization,f"16:9 Part 1",(segment_x_start + 5, 30),font,font_scale,layout_color,font_thickness,)# Second segmentsegment_center_x = original_center_x + segment1_width // 4segment_x_start = int(max(0,min(width - segment2_width, segment_center_x - segment2_width // 2),))segment_x_end = int(min(width, segment_x_start + segment2_width))cv2.rectangle(visualization,(segment_x_start, 0),(segment_x_end, segment2_height),layout_color,thickness,)cv2.putText(visualization,f"16:9 Part 2",(segment_x_start + 5, 60),font,font_scale,layout_color,font_thickness,)else: # aspect_key == "9:16"# For 9:16 (two segments stacked)aspect_9_16 = 9 / 16target_width_9_16 = int(height * aspect_9_16)x_start = max(0,min(width - target_width_9_16,original_center_x - target_width_9_16 // 2,),)x_end = x_start + target_width_9_16aspect_9_10_6 = 9 / 10.6aspect_9_5_3 = 9 / 5.3segment1_width = target_width_9_16segment1_height = int(segment1_width/ (aspect_9_10_6 if layout_type.endswith("var1") else aspect_9_5_3))segment2_width = target_width_9_16segment2_height = int(segment2_width/ (aspect_9_5_3 if layout_type.endswith("var1") else aspect_9_10_6))# First segment (top)segment_y_start = 0segment_y_end = min(height, segment_y_start + segment1_height)cv2.rectangle(visualization,(x_start, segment_y_start),(x_end, segment_y_end),layout_color,thickness,)cv2.putText(visualization,f"9:16 Part 1",(x_start + 5, segment_y_start + 30),font,font_scale,layout_color,font_thickness,)# Second segment (bottom)segment_y_start = segment_y_endsegment_y_end = min(height, segment_y_start + segment2_height)cv2.rectangle(visualization,(x_start, segment_y_start),(x_end, segment_y_end),layout_color,thickness,)cv2.putText(visualization,f"9:16 Part 2",(x_start + 5, segment_y_start + 30),font,font_scale,layout_color,font_thickness,)# Draw twoequalhalfs layoutselif layout_type == "twoequalhalfs":# For 16:9 (two 8:9 segments side by side)aspect_8_9 = 8 / 9segment_height = heightsegment_width = int(segment_height * aspect_8_9)# First segment (left)segment_center_x = original_center_x - segment_width // 2segment_x_start = int(max(0, min(width - segment_width, segment_center_x - segment_width // 2)))segment_x_end = int(min(width, segment_x_start + segment_width))cv2.rectangle(visualization,(segment_x_start, 0),(segment_x_end, segment_height),colors["twoequalhalfs"]["16:9"],thickness,)cv2.putText(visualization,f"16:9 Equal 1",(segment_x_start + 5, 30),font,font_scale,colors["twoequalhalfs"]["16:9"],font_thickness,)# Second segment (right)segment_center_x = original_center_x + segment_width // 2segment_x_start = int(max(0, min(width - segment_width, segment_center_x - segment_width // 2)))segment_x_end = int(min(width, segment_x_start + segment_width))cv2.rectangle(visualization,(segment_x_start, 0),(segment_x_end, segment_height),colors["twoequalhalfs"]["16:9"],thickness,)cv2.putText(visualization,f"16:9 Equal 2",(segment_x_start + 5, 60),font,font_scale,colors["twoequalhalfs"]["16:9"],font_thickness,)# For 9:16 (two 9:8 segments stacked)aspect_9_16 = 9 / 16target_width_9_16 = int(height * aspect_9_16)x_start = max(0,min(width - target_width_9_16, original_center_x - target_width_9_16 // 2),)x_end = x_start + target_width_9_16aspect_9_8 = 9 / 8segment_width_9_16 = target_width_9_16segment_height_9_16 = int(segment_width_9_16 / aspect_9_8)# First segment (top)segment_y_start = 0segment_y_end = min(height, segment_y_start + segment_height_9_16)cv2.rectangle(visualization,(x_start, segment_y_start),(x_end, segment_y_end),colors["twoequalhalfs"]["9:16"],thickness,)cv2.putText(visualization,f"9:16 Equal 1",(x_start + 5, segment_y_start + 30),font,font_scale,colors["twoequalhalfs"]["9:16"],font_thickness,)# Second segment (bottom)segment_y_start = segment_y_endsegment_y_end = min(height, segment_y_start + segment_height_9_16)cv2.rectangle(visualization,(x_start, segment_y_start),(x_end, segment_y_end),colors["twoequalhalfs"]["9:16"],thickness,)cv2.putText(visualization,f"9:16 Equal 2",(x_start + 5, segment_y_start + 30),font,font_scale,colors["twoequalhalfs"]["9:16"],font_thickness,)13 unmodified lines(0, 0, 0),2,)# Convert back to PIL formatvisualization_pil = Image.fromarray(cv2.cvtColor(visualization, cv2.COLOR_BGR2RGB))3 unmodified linesdef get_image_crop(cid=None, rsid=None, uid=None):"""Function that returns both standard and layout variations for visualization.Returns:gr.Gallery: Gallery of all generated images2 unmodified linesimage_paths = get_sprite_firebase(cid, rsid, uid)except Exception:image_paths = ["data/sprite1.jpg", "data/sprite2.jpg"]# Lists to store all imagesall_images = []all_captions = []43 unmodified linesprint(f"Using divisions: left={left_division}, right={right_division}")# Create layouts and cutouts using the new function(standard_crops,threehalfs_layouts,twothirdhalfs_layouts,twoequalhalfs_layouts,visualization_data,) = create_layouts(mid_image, left_division, right_division)# Create all the required visualizations# 1. Standard aspect ratio visualization (16:9 and 9:16)standard_visualization = draw_layout_regions(mid_image, left_division, right_division, visualization_data, "standard")all_images.append(standard_visualization)all_captions.append(f"Standard Aspect Ratios (16:9 & 9:16) {standard_visualization.size}")# 2. Threehalfs visualizationthreehalfs_visualization = draw_layout_regions(mid_image, left_division, right_division, visualization_data, "threehalfs")all_images.append(threehalfs_visualization)all_captions.append(f"Three Halfs Layout {threehalfs_visualization.size}")# 3. Twothirdhalfs var1 visualizationtwothirdhalfs_var1_visualization = draw_layout_regions(mid_image,left_division,right_division,visualization_data,"twothirdhalfs_var1",)all_images.append(twothirdhalfs_var1_visualization)all_captions.append(f"Two-Thirds Halfs Var1 Layout {twothirdhalfs_var1_visualization.size}")# 4. Twothirdhalfs var2 visualizationtwothirdhalfs_var2_visualization = draw_layout_regions(mid_image,left_division,right_division,visualization_data,"twothirdhalfs_var2",)all_images.append(twothirdhalfs_var2_visualization)all_captions.append(f"Two-Thirds Halfs Var2 Layout {twothirdhalfs_var2_visualization.size}")# 5. Twoequalhalfs visualizationtwoequalhalfs_visualization = draw_layout_regions(mid_image,left_division,right_division,visualization_data,"twoequalhalfs",)all_images.append(twoequalhalfs_visualization)all_captions.append(f"Two Equal Halfs Layout {twoequalhalfs_visualization.size}")# Add input and middle image to galleryall_images.append(input_image)2 unmodified linesall_images.append(mid_image)all_captions.append(f"Middle Thumbnail {mid_image.size}")# Add standard cropsfor key, crop in standard_crops.items():all_images.append(crop)all_captions.append(f"{key} {crop.size}")# Add threehalfs layoutsfor key, layout in threehalfs_layouts.items():all_images.append(layout)all_captions.append(f"Three Halfs {key} {layout.size}")# Add twothirdhalfs layoutsfor key, layout in twothirdhalfs_layouts.items():all_images.append(layout)all_captions.append(f"Two-Thirds Halfs {key} {layout.size}")# Add twoequalhalfs layoutsfor key, layout in twoequalhalfs_layouts.items():all_images.append(layout)all_captions.append(f"Two Equal Halfs {key} {layout.size}")# Return gallery with all imagesreturn gr.Gallery(value=list(zip(all_images, all_captions)))
crop_utils.py+985-226