{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.14","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"none","dataSources":[{"sourceId":6818,"databundleVersionId":1960702,"sourceType":"competition"},{"sourceId":6590022,"sourceType":"datasetVersion","datasetId":3795964},{"sourceId":9423075,"sourceType":"datasetVersion","datasetId":3320483}],"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"# Whale Fins to Picture Animation2\n\n","metadata":{"papermill":{"duration":0.004419,"end_time":"2023-05-26T05:44:57.446479","exception":false,"start_time":"2023-05-26T05:44:57.44206","status":"completed"},"tags":[]}},{"cell_type":"markdown","source":"find_closest_color\n\nhttps://www.kaggle.com/code/stpeteishii/nba-movie-to-picture-animation2","metadata":{}},{"cell_type":"code","source":"#!rm -rf frames\n#!rm -rf images","metadata":{"execution":{"iopub.status.busy":"2024-10-02T03:33:18.295398Z","iopub.execute_input":"2024-10-02T03:33:18.295859Z","iopub.status.idle":"2024-10-02T03:33:18.301082Z","shell.execute_reply.started":"2024-10-02T03:33:18.295817Z","shell.execute_reply":"2024-10-02T03:33:18.299815Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import os\nimport shutil\nimport cv2\nimport numpy as np\nimport pandas as pd\nfrom IPython.display import Video\n\nfrom PIL import Image, ImageDraw\nimport matplotlib.pyplot as plt\nimport plotly.express as px\nimport plotly.graph_objects as go\nfrom plotly.subplots import make_subplots\nfrom matplotlib import animation, rc\nrc('animation', html='jshtml')\nfrom sklearn.cluster import KMeans\nimport cv2\nimport os\nimport logging","metadata":{"papermill":{"duration":0.020735,"end_time":"2023-05-26T05:45:32.772864","exception":false,"start_time":"2023-05-26T05:45:32.752129","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2024-10-02T03:33:18.303248Z","iopub.execute_input":"2024-10-02T03:33:18.303754Z","iopub.status.idle":"2024-10-02T03:33:18.319819Z","shell.execute_reply.started":"2024-10-02T03:33:18.303700Z","shell.execute_reply":"2024-10-02T03:33:18.318552Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!mkdir images","metadata":{"execution":{"iopub.status.busy":"2024-10-02T03:33:18.322253Z","iopub.execute_input":"2024-10-02T03:33:18.322763Z","iopub.status.idle":"2024-10-02T03:33:19.431758Z","shell.execute_reply.started":"2024-10-02T03:33:18.322709Z","shell.execute_reply":"2024-10-02T03:33:19.428885Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"paths=[]\nfor dirname, _, filenames in os.walk('/kaggle/input/humpback-whale-identification/test'):\n    for filename in filenames:\n        paths+=[(os.path.join(dirname, filename))]\n\npaths.sort()","metadata":{"execution":{"iopub.status.busy":"2024-10-02T03:33:19.434534Z","iopub.execute_input":"2024-10-02T03:33:19.435159Z","iopub.status.idle":"2024-10-02T03:33:21.324679Z","shell.execute_reply.started":"2024-10-02T03:33:19.435092Z","shell.execute_reply":"2024-10-02T03:33:21.323262Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(len(paths))","metadata":{"execution":{"iopub.status.busy":"2024-10-02T03:33:21.328296Z","iopub.execute_input":"2024-10-02T03:33:21.328726Z","iopub.status.idle":"2024-10-02T03:33:21.335547Z","shell.execute_reply.started":"2024-10-02T03:33:21.328683Z","shell.execute_reply":"2024-10-02T03:33:21.334046Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import matplotlib.pyplot as plt\nimage = plt.imread(paths[0])\nimage = cv2.resize(image,(224,224))\nprint(image.shape)\nplt.imshow(image)\nplt.axis('off')\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2024-10-02T03:33:21.336756Z","iopub.execute_input":"2024-10-02T03:33:21.337159Z","iopub.status.idle":"2024-10-02T03:33:21.601713Z","shell.execute_reply.started":"2024-10-02T03:33:21.337118Z","shell.execute_reply":"2024-10-02T03:33:21.600282Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Finding color clusters","metadata":{}},{"cell_type":"code","source":"pixels = image.reshape(-1,3)\nprint(pixels)\n\nnum_clusters = 12\nkmeans = KMeans(n_clusters=num_clusters, n_init='auto')\nkmeans.fit(pixels*255)\n\ncluster_centers = kmeans.cluster_centers_.astype(int)\nprint(cluster_centers)\nprint(len(cluster_centers))\n\nsegmented_image = cluster_centers[kmeans.labels_].reshape(image.shape)\nplt.figure(figsize=(4,4))\nplt.imshow(segmented_image)\nplt.show()\n\nmasks=list(range(num_clusters))\nfor i in range(num_clusters):\n    masksi = np.all(segmented_image == cluster_centers[i], axis=-1) \n    masks[i] = masksi.astype(np.uint8)*255\n\nmasks2 = np.concatenate(masks, axis=1)\nplt.figure(figsize=(12,4))\nplt.imshow(masks2)\nplt.show()\n\ncluster_centers0=cluster_centers.copy()","metadata":{"execution":{"iopub.status.busy":"2024-10-02T03:33:21.603117Z","iopub.execute_input":"2024-10-02T03:33:21.603507Z","iopub.status.idle":"2024-10-02T03:33:22.266714Z","shell.execute_reply.started":"2024-10-02T03:33:21.603462Z","shell.execute_reply":"2024-10-02T03:33:22.265213Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#print(cluster_centers)\n\nconcatenated_image = np.zeros((2,2*len(cluster_centers),3), dtype=np.uint8)\n\nfor i, color in enumerate(cluster_centers):\n    img = np.full((2,2,3), color, dtype=np.uint8)\n    concatenated_image[:,i*2:(i+1)*2,:] = img\n\nplt.figure(figsize=(12,4))\nplt.imshow(concatenated_image)\nplt.axis('off')\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2024-10-02T03:33:22.268205Z","iopub.execute_input":"2024-10-02T03:33:22.268593Z","iopub.status.idle":"2024-10-02T03:33:22.332054Z","shell.execute_reply.started":"2024-10-02T03:33:22.268553Z","shell.execute_reply":"2024-10-02T03:33:22.330281Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"fig = plt.figure()\nax = fig.add_subplot(111, projection='3d')\nfor x,y,z in cluster_centers:\n    color=np.array([x,y,z])/255\n    print(color)\n    ax.scatter(x,y,z,color=color)\nax.set_xlabel('X Label')\nax.set_ylabel('Y Label')\nax.set_zlabel('Z Label')\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2024-10-02T03:33:22.334170Z","iopub.execute_input":"2024-10-02T03:33:22.337129Z","iopub.status.idle":"2024-10-02T03:33:22.684552Z","shell.execute_reply.started":"2024-10-02T03:33:22.337062Z","shell.execute_reply":"2024-10-02T03:33:22.683298Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"---","metadata":{}},{"cell_type":"markdown","source":"# find_closest_color","metadata":{}},{"cell_type":"code","source":"# Replace each color in B with the closest color in A\ndef find_closest_color(color, palette):\n    distances = np.linalg.norm(palette - color, axis=1)\n    return palette[np.argmin(distances)]\n\n#B_closest = np.array([find_closest_color(color, A) for color in B])\n\ncluster_centers2=np.load('/kaggle/input/color-palette/standard_color14.npy')\n\nmy_cluster_centers = np.array([find_closest_color(color, cluster_centers2) for color in cluster_centers])\nsegmented_image = my_cluster_centers[kmeans.labels_].reshape(image.shape)\nplt.figure(figsize=(4,4))\nplt.imshow(segmented_image)\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2024-10-02T03:33:22.686157Z","iopub.execute_input":"2024-10-02T03:33:22.686648Z","iopub.status.idle":"2024-10-02T03:33:22.945411Z","shell.execute_reply.started":"2024-10-02T03:33:22.686600Z","shell.execute_reply":"2024-10-02T03:33:22.943991Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"---","metadata":{}},{"cell_type":"markdown","source":"# Try replacing the colors using find_closest_color","metadata":{}},{"cell_type":"code","source":"def clustered(path,cluster_centers0):\n    \n    image = plt.imread(path)\n    if len(image.shape) == 2:\n        image = cv2.cvtColor(image, cv2.COLOR_GRAY2RGB)\n    image = cv2.resize(image,(224,224))\n    pixels = image.reshape(-1,3)\n\n    num_clusters = 12\n    kmeans = KMeans(n_clusters=num_clusters, n_init='auto')\n    kmeans.fit(pixels*255)\n\n    cluster_centers1 = kmeans.cluster_centers_.astype(int)\n    \n    # use find_closest_color    \n    cluster_centers = np.array([find_closest_color(color, cluster_centers0) \n                                for color in cluster_centers1])\n\n    segmented_image = cluster_centers[kmeans.labels_].reshape(image.shape)\n    #plt.figure(figsize=(4,4))\n    #plt.imshow(segmented_image)\n    #plt.show()\n\n    masks=list(range(num_clusters))\n    for i in range(num_clusters):\n        masksi = np.all(segmented_image == cluster_centers[i], axis=-1) \n        masks[i] = masksi.astype(np.uint8)*255\n\n    masks2 = np.concatenate(masks, axis=1)\n    #plt.figure(figsize=(4,4))\n    #plt.imshow(masks2)\n    #plt.show()\n    \n    for i in range(num_clusters):\n        #cluster_centers[i]=cluster_centers0[i] ### change body color\n        my_cluster_centers=cluster_centers\n        segmented_image = my_cluster_centers[kmeans.labels_].reshape(image.shape)\n        if i==num_clusters-1:\n            plt.figure(figsize=(3,3))\n            plt.imshow(segmented_image)\n            plt.axis('off')\n            plt.show()\n            segmented_image = segmented_image.astype(np.uint8)\n            plt.imsave(os.path.join('images', path.split('/')[-1]), segmented_image)","metadata":{"execution":{"iopub.status.busy":"2024-10-02T03:33:22.948814Z","iopub.execute_input":"2024-10-02T03:33:22.949710Z","iopub.status.idle":"2024-10-02T03:33:22.962474Z","shell.execute_reply.started":"2024-10-02T03:33:22.949663Z","shell.execute_reply":"2024-10-02T03:33:22.960748Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"cluster_centers0","metadata":{"execution":{"iopub.status.busy":"2024-10-02T03:33:22.964558Z","iopub.execute_input":"2024-10-02T03:33:22.965761Z","iopub.status.idle":"2024-10-02T03:33:22.986040Z","shell.execute_reply.started":"2024-10-02T03:33:22.965712Z","shell.execute_reply":"2024-10-02T03:33:22.984651Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"for path in paths[0:10]:\n    clustered(path,cluster_centers0)","metadata":{"execution":{"iopub.status.busy":"2024-10-02T03:33:22.987596Z","iopub.execute_input":"2024-10-02T03:33:22.988600Z","iopub.status.idle":"2024-10-02T03:33:26.018489Z","shell.execute_reply.started":"2024-10-02T03:33:22.988547Z","shell.execute_reply":"2024-10-02T03:33:26.016871Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# create animation.gif","metadata":{}},{"cell_type":"code","source":"!rm *","metadata":{"execution":{"iopub.status.busy":"2024-10-02T03:33:26.020686Z","iopub.execute_input":"2024-10-02T03:33:26.021452Z","iopub.status.idle":"2024-10-02T03:33:27.097932Z","shell.execute_reply.started":"2024-10-02T03:33:26.021388Z","shell.execute_reply":"2024-10-02T03:33:27.096462Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import glob\nfrom PIL import Image\n\nimage_files = sorted(glob.glob('images/*.jpg'))\nimages = [Image.open(image) for image in image_files]\n\nimages[0].save('animation.gif', save_all=True, append_images=images[1:], duration=800, loop=0)","metadata":{"execution":{"iopub.status.busy":"2024-10-02T03:33:27.100017Z","iopub.execute_input":"2024-10-02T03:33:27.100582Z","iopub.status.idle":"2024-10-02T03:33:27.294862Z","shell.execute_reply.started":"2024-10-02T03:33:27.100518Z","shell.execute_reply":"2024-10-02T03:33:27.293658Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from IPython.display import Image\nImage(open('./animation.gif','rb').read())","metadata":{"execution":{"iopub.status.busy":"2024-10-02T03:33:27.297034Z","iopub.execute_input":"2024-10-02T03:33:27.297568Z","iopub.status.idle":"2024-10-02T03:33:27.319871Z","shell.execute_reply.started":"2024-10-02T03:33:27.297516Z","shell.execute_reply":"2024-10-02T03:33:27.318596Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{"papermill":{"duration":0.07786,"end_time":"2023-05-26T05:56:48.903548","exception":false,"start_time":"2023-05-26T05:56:48.825688","status":"completed"},"tags":[]},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}