<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Robert Davidson on Medium]]></title>
        <description><![CDATA[Stories by Robert Davidson on Medium]]></description>
        <link>https://medium.com/@robertjdavidson?source=rss-e5fa1eb73362------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*mhI_XLlpYVGPrCuw9R9NWQ.jpeg</url>
            <title>Stories by Robert Davidson on Medium</title>
            <link>https://medium.com/@robertjdavidson?source=rss-e5fa1eb73362------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 01:19:29 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@robertjdavidson/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Solving Four Pics One Word with Machine Learning]]></title>
            <link>https://medium.com/@robertjdavidson/solving-four-pics-one-word-with-machine-learning-d66a24b93e74?source=rss-e5fa1eb73362------2</link>
            <guid isPermaLink="false">https://medium.com/p/d66a24b93e74</guid>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[vector-embeddings]]></category>
            <dc:creator><![CDATA[Robert Davidson]]></dc:creator>
            <pubDate>Mon, 15 Jan 2024 08:23:47 GMT</pubDate>
            <atom:updated>2024-01-16T05:06:48.934Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/672/1*N4uJRgGzaaM8gPmGFxnlSg.jpeg" /><figcaption>Four Pics One Word image from Microsoft Store</figcaption></figure><p>Using various machine learning techniques (e.g. computer vision, captioning and vector embeddings) to make predictions for solving levels of the popular game Four Pics One Word.</p><h3>Introduction</h3><p>Four Pics One Word is a captivating and challenging puzzle game developed by LOTUM GmbH that engages players with a simple yet addictive concept. The game presents users with four images that seemingly have no apparent connection at first glance. The goal is to identify the common thread linking these somewhat unrelated pictures. As well as the images, players are provided with two additional clues which are the number of letters in the word as well as twelve available letters that can be used to form the word. Players must leverage their observational skills, creativity, and vocabulary to decipher the hidden word that encapsulates the essence of all four images. Players earn gold coins when they complete levels or when they achieve certain milestones. When players get stuck on a word, they can spend gold on various ‘jokers’ to help them solve the word and additional gold can be purchased if necessary.</p><p>Four Pics One Word is a particular favourite of mine. As I’m writing this article, I’m at around level 5,500 and I’ve been stuck on my fair share of words along the way! Often, when playing the game, the obvious thought would rattle around in my head. How hard would it be to develop something would help me solve levels when I get stuck?</p><h3>Methodology</h3><p>This article discusses an approach for using a range of machine learning techniques to suggest solutions for any level of Four Pics One Word simply by analysing a screenshot. The approach used is in two parts:</p><p>Part 1: Naive Method — find the most common words that can be made using the available letters and number of letters in the desired word.</p><ol><li>Use OpenCV to identify the 12 letters available in the level and to manipulate each line of letters so that they can be ‘read’ by a Object Character Recognition (OCR) library</li><li>Use EasyOCR to ‘read’ the characters from each line to identify the 12 individual letters available for the level</li><li>Use OpenCV to count the number of letters required to form the word</li><li>Use <a href="https://www.kaggle.com/datasets/rtatman/english-word-frequency">English Word Frequency dataset by Rachael Tatmen</a> and filter for all words that are the correct length and that can be formed from the available letters — sorted by frequency of use</li></ol><p>Part 2: Machine Learning Method — build on Part 1 by analysing the available pictures to determine which of the possible words are the best fit for the pictures</p><ol><li>Use OpenCV to isolate the 4 individual pictures</li><li>Using a pre-trained Hugging Face Transformer model to generate a caption for each image</li><li>Use Sentence Transformer to create embeddings for the possible words</li><li>Use each caption as a prompt in a semantic search against the embeddings for the possible words to create a new list from the possible words along with the average probability for each word that it is a match for the four pics.</li></ol><h3>Analysis</h3><p>TL;DR To skip the analysis and see it in action, navigate to <a href="https://huggingface.co/spaces/robertjd/four-pics-one-word">this space on Hugging Face</a> to give it a go. Choose from an example or upload a screenshot of your own. The results for the examples are cached but if you upload your own screenshot, please be patient as it takes a minute or two for the analysis to complete.</p><p><a href="https://huggingface.co/spaces/robertjd/four-pics-one-word">Four Pics One Word - a Hugging Face Space by robertjd</a></p><p>The full notebook can found on Kaggle:</p><p><a href="https://www.kaggle.com/code/robertjdavidson/four-pics-one-word-solver">Four Pics One Word Solver</a></p><p>Using this level as an example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7dq9MSraqP5jzQjjDNEK3g.png" /><figcaption>Figure 1: An example screen shot that is used in detail below</figcaption></figure><h4>Part 1: Naive Method</h4><p>In Part 1 of the analysis, only the available letters and the number of letters in the word are considered. This is very much the brute force method where we filter a large set of english words (along with their frequency of use) looking for all words that are the same length as the word we are searching for. Using this new subset of words, we further filter it down to include only those words that can be made up of the available letters. Finally, we sort the available words by the frequency of use.</p><h4>Step 1: Use OpenCV to isolate the 2 rows of letters (including reducing spacing) and use EasyOCR to read the available letters</h4><p>Using OpenCV, the image is converted to grayscale so that there is only one channel in the image making it easier to work with. The letters are isolated by creating a mask which makes the letters black and everything else white.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Eo8ya_7NA43wF1r24DcZEQ.png" /><figcaption>Figure 2: Isolating the letters from the image using OpenCV</figcaption></figure><p>Next, most of the white space is removed between letters to make it easier for EasyOCR to read the letters. EasyOCR has likely been trained on words and not individual letters.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/526/1*6hTCyBEWLiEisuC6ViEGDQ.png" /><figcaption>Figure 3: Line 2 with most of the white space removed</figcaption></figure><pre>reader = easyocr.Reader([&#39;en&#39;])<br><br>def read_available_letters(image: np.array) -&gt; List[str]:<br>    img_cropped = image[int(image.shape[0] * 0.7):image.shape[0], 0:image.shape[1]]<br>    greyscale = cv2.cvtColor(img_cropped, cv2.COLOR_BGR2GRAY)<br>    img = cv2.inRange(greyscale, np.array(40), np.array(50))<br>    img = (255 - img)<br>    results = reader.readtext(img, detail=1, allowlist=string.ascii_uppercase)<br>    text = __read_letters_for_line(img, results[0]) + __read_letters_for_line(img, results[-1])<br>    return [value for value in list(text)]<br><br>def __read_letters_for_line(image: np.array, result) -&gt; List[str]:<br>    line = image[int(result[0][0][1]) - 10:int(result[0][2][1]) + 10, 0:int(image.shape[1])]<br>    idx = np.argwhere(np.all(line[..., :] == 255, axis=0))<br>    for i in range(5, 10):<br>        idx = idx[np.array(idx) % i != 0]<br>        line1 = np.delete(line, idx, axis=1)<br>        display_img(line1)<br>        letters = reader.readtext(line1, detail=0, allowlist=string.ascii_uppercase)[0]<br>        if len(letters) == 6:<br>            return letters<br>    return []</pre><h4>Step 2: Use OpenCV to count the number of boxes (i.e. the number of letters in the word)</h4><p>Working with the image in grayscale, the image is manipulated to isolate the borders for each empty letter block which can then be counted.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oKeF-CO4roJUiBEZvPL1MA.png" /><figcaption>Figure 4: Shows the empty letter boxes isolated in a way that can be counted.</figcaption></figure><pre>def count_boxes(image: np.array) -&gt; int:<br>    img = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)<br>    img_cropped = img[int(image.shape[0] * 0.61):int(image.shape[0] * 0.72), 0:image.shape[1]]<br>    img_blurred = cv2.GaussianBlur(img_cropped, (11, 11), 0)<br>    img_canny = cv2.Canny(img_blurred, 10, 100, 3)<br>    img_dilated = cv2.dilate(img_canny, (1, 1), iterations=0)<br>    display_img(img_dilated)<br>    (cnt, hierarchy) = cv2.findContours(img_dilated.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)<br>    return len(cnt)</pre><h4>Step 3: Find all words of the right length that can be formed with the available letters</h4><p>Load the English words dataset then filter for all of the words that match the required length and finally, filter for all words than can be formed from the available letters.</p><pre>def load_words():<br>    df = pd.read_csv(‘/kaggle/input/english-word-frequency/unigram_freq.csv’)<br>    df[‘length’] = df[‘word’].str.len()<br>    return df<br><br>def filter_fn(row, letters):<br>    chars = [*letters]<br>    word = row[&#39;word&#39;]<br>    for c in [*word]:<br>        if c in chars:<br>            chars.remove(c)<br>        else:<br>            return False<br>    return True<br><br>def solve_naive(length, letters, starts_with=None):<br>    length = int(length)<br>    letters = letters.lower()<br>    words = load_words()<br>    filtered_words = words[words[&#39;length&#39;] == length]<br>    if starts_with:<br>        starts_with = starts_with.lower()<br>        filtered_words = filtered_words[filtered_words[&#39;word&#39;].str.startswith(starts_with)]<br>    return filtered_words[filtered_words.apply(filter_fn, letters=letters, axis=1)]</pre><h4>Example</h4><p>The following example is from level 5350 and the solution is <strong><em>stomach</em></strong>.</p><pre>solve_naive(7, &#39;OSEMACKHAWCT&#39;)</pre><p>Which yields the following result (top 10 predictions shown):</p><pre>          word     count  length<br>1737   watches  47364531     7.0<br>3057   matches  25196889     7.0<br>7463   coaches   7744876     7.0<br>7837   stomach   7234044     7.0 (the correct prediction is 4th)<br>14970  catches   2615877     7.0<br>16775  comcast   2160724     7.0<br>22677  mathews   1288615     7.0<br>35933  choctaw    587588     7.0<br>38955  wasatch    512195     7.0<br>44592  whatcom    405217     7.0<br>.....</pre><h4>Part 2: Machine Learning Method</h4><p>In Part 2 of the analysis, an attempt is made to outperform the naive method using various machine learning techniques to determine what clues are being presented in the pics and see which of the possible words would make the best prediction.</p><h4>Step 1: Use OpenCV to isolate the 4 individual pictures</h4><p>Using OpenCV, the image is converted to grayscale so that there is only one channel in the image making it easier to work with. Each picture is surrounded by a border which is isolated using a mask to make it more suitable for isolating.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/863/1*cPLDy91JuHmapOtVTM0z8w.png" /><figcaption>Figure 5: Using OpenCV to highlight the border for image extraction</figcaption></figure><pre>def get_pics(image: np.array) -&gt; List[np.array]:<br>    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)<br>    threshold = cv2.inRange(gray, np.array(55), np.array(70))<br>    threshold = (255 - threshold)<br>    all_contours, _ = cv2.findContours(threshold, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)<br>    areas = []<br>    contours = []<br><br>    for contour in all_contours:<br>        area = cv2.contourArea(contour)<br>        areas.append(area)<br>        contours.append(contour)<br><br>    pics = []<br>    df = pd.DataFrame({&#39;area&#39;: areas, &#39;contours&#39;: contours}).sort_values(by=&#39;area&#39;, ascending=False).reset_index()<br>    for index in range(1, 5):<br>        x, y, w, h = cv2.boundingRect(df.loc[index][&#39;contours&#39;])<br>        pic = image[y:y + h, x:x + w]<br>        pics.append(pic)<br>    return pics</pre><h4>Step 2: Using a pre-trained Hugging Face Transformer model to generate a caption for each image</h4><p>In this case, a pre-trained model from <a href="https://huggingface.co/Salesforce/blip-image-captioning-large">Salesforce via Hugging Face</a> is used to generate captions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/741/1*7oT0az_MD9xQcUInlSM4Rg.png" /><figcaption>Figure 6: Each separate pic with the caption generated by the pre-trained model</figcaption></figure><pre>processor = BlipProcessor.from_pretrained(&quot;Salesforce/blip-image-captioning-large&quot;)<br>model = BlipForConditionalGeneration.from_pretrained(&quot;Salesforce/blip-image-captioning-large&quot;).to(device)<br><br>def caption_image(image: np.ndarray) -&gt; str:<br>    inputs = processor(image, return_tensors=&quot;pt&quot;).to(device)<br>    out = model.generate(**inputs)<br>    caption = processor.decode(out[0], skip_special_tokens=True)<br>    return caption</pre><h4>Step 3: Use Sentence Transformer to create embeddings for the possible words and conduct a semantic search using each caption as a prompt to make the best prediction from the possible words</h4><p>In this case, a pre-trained model called <a href="https://huggingface.co/sentence-transformers/all-mpnet-base-v2">all-mpnet-base-v2 via Hugging Face</a> is used with SentenceTransformer to generate the embeddings and to undertake the semantic search for each caption.</p><pre>embedding_model = SentenceTransformer(&#39;all-mpnet-base-v2&#39;)<br>embedding_size = 768<br><br>def search(prompts: List[str], corpus: List[str], top_k=10):<br>    corpus_embeddings = embedding_model.encode(corpus, show_progress_bar=False)<br>    words = []<br>    scores = []<br>    for prompt in prompts:<br>        prompt_embedding = embedding_model.encode(prompt, show_progress_bar=False)<br>        hits = util.semantic_search(prompt_embedding, corpus_embeddings, top_k=top_k)[0]<br>        for hit in hits[0:top_k]:<br>            words.append(corpus[hit[&#39;corpus_id&#39;]])<br>            scores.append(hit[&#39;score&#39;])<br>    return pd.DataFrame({&#39;word&#39;: words, &#39;score&#39;: scores})</pre><h3>Results</h3><p>The results of the approach to use machine learning to solve Four Pics One Word levels are encouraging. A total of 254 levels were analysed and the results are as follows:</p><h4>Accuracy</h4><p>As this isn’t a typical ML task, the accuracy can be described in a number of ways:</p><p>Predicting the correct word (on the first attempt):<br>Naive: 22.05%<br>ML: 75.20%</p><figure><img alt="Accuracy of ML and Naive approaches shows that the accuracy of the ML method is significantly higher than Naive method." src="https://cdn-images-1.medium.com/max/640/1*u-SyBVfuYbqnyOahVwN4sA.png" /><figcaption>Figure 7: Accuracy of ML and Naive approaches</figcaption></figure><p>Considering the ML approach specifically (over 254 levels):<br>Better than naive: 67.72% of the time<br>Same as naive: 18.11% of the time<br>Worse than naive: 13.78% of the time</p><h3>Conclusion</h3><p>Using a Machine Learning approach to solving Four Pics One Word was significantly more effective than a simple naive approach. Using freely available pre-trained models to generate captions and then embeddings that can be quickly searched to make predictions proved to be a relatively straightforward yet successful approach.</p><p>Source code can be found on Hugging Face:</p><p><a href="https://huggingface.co/spaces/robertjd/four-pics-one-word/tree/main">robertjd/four-pics-one-word at main</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d66a24b93e74" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>