<?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 Amos Stailey-Young on Medium]]></title>
        <description><![CDATA[Stories by Amos Stailey-Young on Medium]]></description>
        <link>https://medium.com/@amosstaileyyoung?source=rss-d901c66b4ae7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*xUC_0O0ikZTz5zJgkdsmkQ.jpeg</url>
            <title>Stories by Amos Stailey-Young on Medium</title>
            <link>https://medium.com/@amosstaileyyoung?source=rss-d901c66b4ae7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 13:52:52 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@amosstaileyyoung/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[Calculated Transparency: Framing in the Films of Christopher Nolan]]></title>
            <link>https://medium.com/@amosstaileyyoung/christopher-nolan-a-style-of-calculated-transparency-07df959f924b?source=rss-d901c66b4ae7------2</link>
            <guid isPermaLink="false">https://medium.com/p/07df959f924b</guid>
            <category><![CDATA[cinema]]></category>
            <category><![CDATA[film]]></category>
            <category><![CDATA[christopher-nolan]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Amos Stailey-Young]]></dc:creator>
            <pubDate>Thu, 19 Mar 2026 20:55:29 GMT</pubDate>
            <atom:updated>2026-04-28T19:50:14.001Z</atom:updated>
            <content:encoded><![CDATA[<h4>A Data Analysis using CineFace</h4><p><em>A big part of my interest in filmmaking is an interest in showing the audience a story through a character’s point of view. It’s interesting to try and do that and maintain a relatively natural look. — </em>Christopher Nolan</p><p>Christopher Nolan is one of the more well-known and respected directors in contemporary Hollywood. He has gained a reputation for narratives that play with the nature of temporality and causality — the reverse chronology of <em>Memento</em> (2000) being a prime example — and that center on themes of identity, memory, and time.</p><p>Because of the consistency of these themes throughout his work, and because he has written or co-written all of his films (with the exception of <em>Insomnia</em> [2002]), he is generally regarded as a modern-day auteur who places his personal stamp on his films.</p><p>Yet despite his status — or, perhaps, because of it — many critics have criticized his work, particularly regarding what I’ll call “spatial realism,” that his compositions do not always adhere to the standards of “classical continuity” (respect for the 180 degree rule, consistent screen direction, eyeline matches, etc.), making them (at times) spatially incoherent.</p><p>This perspective is best represented by Jim Emerson and his <a href="https://vimeo.com/28792404">video essay</a> on <em>The Dark Knight</em> (2008). Emerson makes a compelling argument that Nolan does not respect spatial realism. I will not be challenging this point. What I will be challenging in this post, however, is that Nolan does not have a distinct visual style.</p><p>If there’s one word that sums up critical appraisals of Nolan’s aesthetic, it would be “transparent.” In his book <em>Christopher Nolan: A Labyrinth of Linkages, </em>film scholar David Bordwell refers to Nolan’s filmmaking technique as a “style without a style.” In other words, his style doesn’t call attention to itself but simply conveys narrative information in as straightforward a manner as possible.</p><p>Per Bordwell, Nolan is an adherent to “intensified continuity,” the dominant style of contemporary Hollywood, which has these four consistent features: rapid editing, bipolar extremes of lens lengths, closer framing in dialogue scenes, and a free-ranging camera. Because of this adherence, Bordwell says that “film style won’t by and large be [Nolan’s] claim to fame.”</p><p>I agree that Nolan largely fits this mold. But I disagree on Bordwell’s characterization of Nolan’s “stylistic choices [as] tidily traditional.” Nolan’s style is, in fact, statistically exceptional within this framework.</p><p>In this post, I’ll argue that Nolan is a contradiction. Watching his films, it’s hard to disagree with Bordwell that his is a style without a style. His shots rarely call attention to themselves, as he prefers the viewer’s attention to be concentrated on the story.</p><p>And yet, the way Nolan frames faces in his films is anything but average. On a few important measures, he is an outlier — an exception, not the rule. He takes the dominant style of contemporary Hollywood and adheres to it more rigidly than any of the over 300 directors I examined. The way that Nolan frames the human face within the image is one of the most statistically extreme not just in contemporary Hollywood, but in all of the sample.</p><p>Nolan is not transparent because he’s simply average or because he’s “sloppy.” Instead, Nolan rigidly adheres to a particular style, one that puts the human face front and center in as “natural” a way as possible. Nolan does this by (literally) centering his faces more than any other director in the sample. This is transparency achieved, not transparency by accident. Because of this, I call Nolan’s style <em>calculated transparency</em>.</p><h3>The Data</h3><p>To accomplish this analysis, I’m using my <a href="https://github.com/astaileyyoung/CineFace">CineFace</a> repository, which contains facial data on over 6,000 films throughout the entire course of cinema history. I employ a variety of statistical measures — relative face size, distance to center, number of faces on-screen, equality of composition — to demonstrate one incontrovertible finding: Christopher Nolan likes to center his faces more than any other director in the sample. But before starting the analysis, there are two important caveats.</p><p>First, the data I’m using only concerns the size and position of the human face within the frame. I do not consider the role of editing, camera movement, or lighting, all of which are important for characterizing a director’s style.</p><p>Secondly, while I have over 300 directors in my sample, it’s not a comprehensive list — hundreds more directors could reasonably be added to it. However, I’ve made an effort to include some of the most famous and respected directors in cinema. A comprehensive list of directors can be found <a href="https://raw.githubusercontent.com/astaileyyoung/CineFace/refs/heads/research/research/baselines/data/director_list.txt">here</a>. If you’d like to explore the notebook used for this analysis, it can be opened in Google Colab <a href="https://colab.research.google.com/github/astaileyyoung/CineFace/blob/main/research/profiles/directors/christopher_nolan.ipynb">here</a>. Again, my CineFace repo is <a href="https://github.com/astaileyyoung/CineFace">here</a>.</p><p>With those concerns out of the way, let’s get to the data.</p><h3>Scale</h3><p>The first metric I’ll examine is face scale, the relative size of the face in an image (face area / image area). So what makes Nolan so distinctive in relation to his peers? Let’s take a look at the average face size in his movies plotted against the variance in that size.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3IgqTvqJbNKKbtSClmV2hQ.png" /></figure><p>Regarding the average size of faces in his films, Nolan is an outlier. He’s in the 98.8 percentile of directors on this metric.</p><p>But there is something else notable about the plot. There is a very strong relationship between the average size of the face and the variance in face sizes (correlation of 0.93). What’s interesting is that Nolan sits well below the regression line, having one of the most negative<em> residuals</em> of any director in the sample.</p><p>What does this mean? While Nolan likes large faces, he does not frequently use extreme close-ups, instead preferring “bust” shots. Nolan reserves extreme close-ups for important narrative moments, such as in our introduction to the Joker in <em>The Dark Knight </em>(2008).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9I7ThU98iMl3ZoMInnTN7w.png" /></figure><p>(An interesting note: the director with the highest residual is Sergio Leone, which makes perfect sense as he contrasts extreme close-ups with expansive landscapes, such as in <em>The Good, the Bad, and the Ugly </em>[1966].)</p><p>Especially in his early career, Nolan eschews establishing shots, preferring instead to cut directly to close-ups. The sequence from <em>Memento</em> below is typical of this pattern.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2fvb6FHO08fyjvdU3dsr6g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M5nI6tWnXuuEiwhDd9i-5Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g-HBZHJKRLp1HMg1iGPp0g.png" /><figcaption>Nolan goes straight from this close-up of the photograph to one of Leonard (Guy Pearce) entering the restaurant without establishing shot. Nolan does pull out briefly to a medium shot, but only just enough to ground his interaction with Natalie (Carrie-Ann Moss).</figcaption></figure><p>Why might Nolan prefer large faces? Returning to the quote at the beginning of the post, his narratives are often about the psychology of his central characters. We see the world from their points-of-view, figuratively if not always literally.</p><p>Nolan’s tendency for tight framings without establishing shots often has the effect of isolating characters from their surroundings. This theme of isolation permeates his earlier works. For instance, in his first feature, <em>Following</em> (1998), Nolan uses a telephoto lens to focus on the protagonist, separating him from the crowd.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SvxO0CvvzNWe02fsQy3RJw.png" /></figure><p>This same sense of isolation is present in <em>Memento. </em>The plot is about a character with anterograde amnesia, which prevents him from forming new memories. The film is told in reverse chronological order, placing the viewer in a disorienting position similar to that of the protagonist. The incessantly tight close-ups add to this sense of disorientation.</p><p>In Nolan’s next film, <em>Insomnia,</em> the protagonist is similarly alienated from his environment. The main character, Will Dormer (played by Al Pacino), has been called from Los Angeles to a remote Alaskan town to investigate a murder. Our first introduction to him is in a tight closeup.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pT7BsYDHovSr_XE4zlC1Qg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wOI67zFRfD3lnxnB5EWGBQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t_1KAPr1zfm725uhh2muMQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LY_ba_tSdL6fG3v3GKrCcA.png" /></figure><p>Nolan immediately places us in the position of the protagonist by giving him a point-of-view shot. He then cuts to the plane flying over the cold, desolate, strangely beautiful landscape, contrasting the expansive environment with the intimacy of the close-ups.</p><p>The style matches the plot of the film. As per the title, Dormer suffers from insomnia during the eternal brightness of Arctic summer. Dormer’s alienation from his environment increases throughout the film as his mental state deteriorates, and the disorienting framing and editing places the viewer inside this alienation.</p><p>Very rarely do we get shots of Dormer within the setting. Instead, Nolan likes to go straight to close-ups (or bust shots).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fB44B_SbbBSeSIIObiLQWA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5GJrK9FeAmjElWmPnbGXhA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LDeHVK6jfLm6OD9_3Um4Rg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y13IksJ_hugH4ShWAfYT2A.png" /><figcaption>The over-the-shoulder shot is the closest we get to a two-shot in this scene.</figcaption></figure><p>In the example above, we cut directly from the car to Dormer in the police station. There is no establishing shot that shows us the spatial relationship between the characters. We don’t even get a two-shot that places Dormer with another character in the frame.</p><p>While Nolan’s average face size is high, it’s largely because he rarely pulls out to long-or-medium shots, not because he favors extreme close-ups in the style of, say, Sergio Leone.</p><p>One note. I’ve focused on his early films here for a reason, something I’ll get to later in the post.</p><h3>Density</h3><p>By “density,” I mean the concentration of faces in the frame. For this calculation, all I’ve done is average the number of faces, excluding empty frames.</p><p>Bordwell says that Nolan has a “preference for cutting together singles.” So what does the data have to say?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wPduvhhzylCldIoC7i59YQ.png" /></figure><p>The data bears out Bordwell’s argument. Nolan sits in the top left corner, meaning he has a low value on average faces per frame and a high value for the percent of frames that are singles (frames with only one face in them). On faces per frame, Nolan is in the bottom 2.2 percent, lower than the vast majority of directors in the sample. On percent singles, Nolan is in the 99.4 percent. Only two directors in the sample have a higher preference for single shots (Ethan Coen and Sydney Pollack).</p><p>Nolan simply does not like to pack the frame with faces. Nor does he frequently use two-shots. Nolan almost always prefers a large, single face. The data has confirmed Bordwell’s intuition. But the significance of the data is not just that it confirms his argument; it shows us <em>how much </em>Nolan prefers singles— more than almost any other director in the sample.</p><h3>Composition</h3><p>So Nolan is an outlier in both scale and density. However, this alone is not what makes him distinctive: it’s the combination of those factors with his rigid compositions. Below is a plot of the average distance of faces to the center of the frame vs. “dispersion.” (See the appendix for how this is calculated.)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GkWtpkmwmVFCKdARuVg8_A.png" /></figure><p>Dispersion measures how spread out the faces are across the screen. On this metric, Nolan is in the bottom 1.5 percent, meaning his compositions are much more concentrated than average. As mentioned above, one explanation for this extreme value is Nolan’s reticence to pack the frame with faces and his preference for singles.</p><p>So Nolan likes to “concentrate” his framings much more than the average director. What does this mean? Well, let’s take a look at his score on the average distance of a face to the center of the image. His score is negative, which means that he, on average, has a <em>shorter</em> distance than any other director — and by a lot.</p><p>A related metric is Gini score, which is another way of measuring the concentration of faces in the frame (I’ll explain how it works shortly). On this metric, the difference between Nolan and the rest of the sample is even more extreme.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QZMnyjj53reis2Mpb1Nqvg.png" /></figure><p>Nolan is practically in his own universe, a full standard deviation away from the next closest director on average distance.</p><p>His low dispersion, high gini, and low distance all point to one thing: Nolan likes the center of the frame. Bordwell intuits this, saying that Nolan’s “films often display the same tendency toward loose, roughly centered framings.” The data does not just suggest that Nolan <em>tends</em> toward “roughly centered framings,” but that he prefers them more than any other director in the sample.</p><p>Now to explain the Gini score. It’s a measure of inequality, originally used for income inequality. So what do I mean when I say that Nolan has incredibly high inequality? It’s a measure of how evenly faces are distributed across a 3x3 grid. A Gini score of 1 would mean that all faces are concentrated in a single cell and a score of 0 would mean that the faces are distributed perfectly equally across the grid. Below is the grid representing all films in the sample. (See appendix for how Gini score is calculated.)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3f0NdFFHQG-yCcO4XLEPLg.png" /></figure><p>As you can see, over half of all face locations occur in either the middle-top or middle-center cells. When we examine the grid for Nolan’s films, the difference between him and the industry baseline is immediately apparent.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WrCJIReZfqjPlGM55V55gQ.png" /></figure><p>Nolan doesn’t just like the center of the frame: he places half of all faces in that cell. The difference between Nolan and the industry baseline is even more obvious if we take the difference between the two grids.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nCe00651l1459PP4ynfO7w.png" /></figure><p>Nolan’s difference with the industry average is 25%, making him twice as likely to put a face in the center of the image than his peers.</p><p>So why might Nolan have such a preference for centered framings? One explanation is that Nolan forms a deliberate contrast between the complexity of his narratives with the simplicity of his compositions. This way, he can tell the story “through the point of view of a character” while maintaining “a relatively natural look.”</p><h3>Career</h3><p>So far, we’ve only looked at Nolan’s career as a whole. What if we examine how his style has changed film by film? When we examine metrics like face scale, density, and composition, an interesting picture emerges. On a couple of metrics, Nolan’s style has changed considerably over his career.</p><p>The table below shows the percentile for each of Nolan’s films on a variety of metrics.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/978/1*G2ZbM1zTpYeF1W8ZmmpmCA.png" /></figure><p>Perhaps the most interesting metric is face scale. If we examine how the size of the face changes over his career, we see a very clear downward trend.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EeY__vEzUhr0Vzm_B8fS3A.png" /></figure><p>Nolan’s style has changed considerably as his career has progressed, moving from an extremely high average face size to essentially average for his last five films (with the exception of <em>Interstellar</em> [2014]), sitting around a Z score of 0. His average is being pulled up by a few extreme films from early in his career.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oPkgbtCBCfFwkfv_ylDUqA.png" /></figure><p>What might account for this shift? One possible explanation is that Nolan has moved away from his large, centered faces because he places more faces in the frame. This seems partly true: face scale and density are inversely correlated (-0.67). One of the main reasons for the decline in average face size is due to placing more faces within the frame.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x1dQv1uYRgBaa7sIz12dDw.png" /></figure><p>This isn’t that surprising. If more faces are in the frame, it’s harder to put them in the center.</p><p>What about his compositions? Are Nolan’s images becoming less centered because his faces are smaller? Let’s look at average face size plotted against Gini score.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J8y0IV7tWjSxtY4BeoLBhg.png" /></figure><p>The data is not so clear cut here. Interestingly, there is a correlation between Gini and face scale at the beginning of his career, but this becomes slightly uncoupled after <em>The Dark Knight </em>(2008). Over his last four films, Nolan has returned to his more concentrated framings (correlation of 0.53 before <em>The Dark Knight</em> vs 0.26 after). The exception is <em>Dunkirk</em>, which makes sense given the subject of the film (war) and the necessity of showing the characters move through the battlefield. But while his Gini score has ticked back up, his average face size has not.</p><p>Gini score is even more inversely correlated with faces per frame (-0.8) than with face scale. This is rather intuitive: multiple faces cannot all be centered. However, what’s notable about Nolan is the sample-wide correlation between Gini score and faces per frame. While still inversely correlated (-0.49), it’s considerably lower than Nolan’s — almost by half.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KXroBMniuNSFhlFT2Khhhw.png" /></figure><p>If we examine the correlations between the variables, a few things stand out. One is the extreme relationship between Gini score and average distance. This is also intuitive. As we’ve already seen, Nolan packs his faces in the center of the image. For this to occur, the distance to center has to be low.</p><p>Distance is also highly correlated with faces per frame. In order to place more faces in the frame, they have to be moved further from the center.</p><p>What’s interesting is the difference between these correlations and the rest of Nolan’s peers. While distance and Gini are correlated in the sample, they are not to the same degree as with Nolan. This becomes clear if we take the difference between the two heatmaps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Td79Qrw3aBOgslF7Hvow_w.png" /></figure><p>Two things stand out. The first is the relationship between distance and “vertical discipline” (a measure of how spread out the faces are across the y axis; a high value means less variation, a low value more variation). Again, knowing that Nolan likes the center of the frame, this makes intuitive sense. Because he’s not placing nearly as many faces in the middle-top of the frame as most of his peers, there is less variation vertically. The only way to decrease the vertical discipline (higher variance) would be to move faces to either the middle-top or middle-bottom cells, something we’ve seen Nolan is loath to do.</p><p>The second is the relationship between distance and Gini score. These variables are correlated in the sample as well (-0.53), but not nearly to the same degree as Nolan (-0.98). The correlation is almost perfectly inverse, again due to Nolan’s extreme preference for the center of the frame. In order to increase the distance, he would have to put the face in a different cell.</p><p>But Nolan’s Gini score is still high in his later films. Combined with our knowledge of the other metrics, we can conclude one thing: in his most recent films, Nolan has not moved faces out of the center of the frame, <em>but has simply moved his camera further back</em>.</p><h3>Explanation</h3><p>The data shows us <em>what </em>changed and <em>how </em>it changed over time, but it does not show us <em>why </em>these changes occurred. To do that, we need a qualitative analysis. I will present a few possibilities to explain the changes in Nolan’s framing.</p><h4>Regression to the Mean</h4><p>This isn’t really a causal explanation — more of a statistical tendency. Since Nolan started off so high on metrics like average face size and Gini score, he had nowhere to go but down, bringing him closer to the mean.</p><p>This is not a very satisfying explanation. Some directors remain remarkably consistent across their careers while others don’t. So what accounts for this discrepancy? Examining the data alone cannot answer that question.</p><p>One way to think of why there might be regression to the mean is that the scale of his productions has increased over his career. In his early films, he worked with lower budgets. A lower scale of production often means fewer creative voices, meaning the director may have more control than in a larger production. It’s possible this applies to Nolan, that he has moved closer to the industry baseline as more and more personnel work on his films. The Batman movies were large-scale studio blockbusters that had different expectations compared to his more personal films. This possibly had the effect of diluting his personal style.</p><p>This argument is problematic, however. Although there’s been movement toward the mean on some metrics, others have largely remained stable. In particular, although there was a decline in Gini score from his early films, it has risen again while average face size has remained around the mean. If regression to the mean is what’s “causing” the decline in face scale, why doesn’t it apply to all metrics?</p><h4>Camera</h4><p>Nolan has famously used IMAX cameras in his films starting with <em>The Dark Knight</em>. Is it possible that his adoption of IMAX changed his filming style? It’s definitely possible given the data. Let’s look at the stats of IMAX movies vs. non-IMAX movies.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/484/1*joRkW9SOO0hwa17y-1M9sg.png" /><figcaption>Nolan mixes IMAX and 35mm formats in his films, so the aggregation is by all movies that have an IMAX camera, regardless of whether it is the only camera used.</figcaption></figure><p>Well look at that. Case closed. His IMAX movies have considerably lower average face sizes compared to his non-IMAX movies.</p><p>But not so fast. All this shows is that there is a correlation; it does not mean IMAX cameras “caused” the change in average face size. As we’ve seen, there is a strong historical trajectory from higher to lower average face sizes in Nolan’s career. It’s entirely possible that Nolan just happened to switch to IMAX at the moment his style was changing. In other words, it’s a coincidence.</p><p>There is one strong reason to think that IMAX did not cause the change in Nolan’s style: the trajectory of his films was trending downward long before he adopted IMAX.</p><p>Maybe there actually is a causal relationship between his adoption of IMAX and his decline in average face. But maybe the causality runs the other way. Perhaps Nolan adopted IMAX because it better fit his new filming style.</p><p>But this explanation is also problematic because there’s no reason to assume that IMAX should lead to smaller face sizes. Yes, IMAX cameras in Nolan’s movies are (occasionally) used to depict expansive landscapes. But Nolan also uses them in very close, intimate framings. In fact, the dimensions of IMAX are actually conducive to larger face sizes because the aspect ratio of the frame is closer to that of the typical face. (This point is questionable since Nolan’s cinematographer Hoyte van Hoytema has said that there needs to be more “headroom” in IMAX since the screen is so much taller.)</p><p>The “technological deterministic” argument is somewhat weak. Although there is a inverse relationship between IMAX and face scale in Nolan’s films, this does not hold true for the rest of the sample.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/505/1*1mT2r8f8ffuaSigF5ESVaw.png" /><figcaption>There is a wild discrepancy in Gini and distance between camera formats, which is interesting.</figcaption></figure><p>Yes, there is a slight difference in face scale between camera formats, but not an exceptional one. The discrepancy in Nolan’s films is much more extreme than that found in the wider sample.</p><p>There is one conceivable way to investigate the effect of IMAX on Nolan’s framings. That would be to compare the differences in framing by camera <em>within the same movie. </em>That would filter out our problem with Nolan’s historical trajectory.</p><p>There is one significant problem, however: I don’t have that kind of data. My metadata for the movies depends on IMDb. While it lists the cameras used for a film, it does not say which sequences belong to which cameras. To compare, I would need to be able to connect a specific face to a specific camera. It might be conceivable that I could do this manually since an easy way to spot the IMAX sequences is the aspect ratio. But this would involve considerable work meticulously labeling sequences by camera. Unfortunately, I don’t have that kind of time.</p><h4>Personnel</h4><p>Could the change in Nolan’s style be attributed to a change in personnel? It’s definitely possible: cinematographers bear a lot of responsibility for how a film looks. Nolan has famously used only two cinematographers (I’m excluding <em>Following</em> since that was not a studio film): Wally Pfister and Hoyte van Hoytema. Let’s compare the two.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/713/1*B-0M2aAfotU5UXzSj9XLvg.png" /></figure><p>There is a significant difference between them on most of the metrics. In particular, there is a huge discrepancy between the cinematographers in terms of face scale. Wally Pfister is two whole standard deviations from Hoyte van Hoytema on this metric.</p><p>But we have the exact same problem as with the change in cameras. There is a strong correlation, but we cannot determine causation. Perhaps Nolan’s switch in cinematographers did drive his stylistic evolution. But it’s just as possible that Nolan switched cinematographers to fit his new style. Or, perhaps there is, in fact, absolutely no relationship — it’s all coincidental.</p><p>There is one way we can try to determine this. That is to examine the cinematographers on films that are not Nolan’s. Let’s take a look.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/713/1*iMppMPU37vYflBkmkYFqYw.png" /></figure><p>There are significant differences between the two on most metrics. Interestingly, van Hoytema actually has a higher average face size than Pfister does, despite the relationship being reversed in Nolan’s films.</p><p>There is one significant problem with this analysis: sample size. All but three of van Hoytema’s films in the sample are on movies not directed by Nolan, and all but two of Pfister’s were. Nevertheless, the examination does undermine the personnel argument.</p><h4>Stylistic Evolution</h4><p>This explanation is rather straightforward: Nolan’s style has changed because his filmmaking techniques have evolved throughout his career. If this is the case, there is no “external” factor driving these changes — they are intrinsic to Nolan’s style. Another way to put it is that the only person who knows why Nolan’s style has changed is Christopher Nolan himself.</p><p>So let’s say for the moment that Nolan’s style has changed due to the subject matter of his films. There may be some truth to this. I mentioned before that the theme of isolation and alienation permeates his early work. His filmmaking style — close, centered framings — has the effect of isolating characters from their environments. As he switched to higher budget, blockbuster action films, he had to pull the camera back for action sequences. The films that buck the trend — <em>Inception </em>(2010) and especially <em>Interstellar</em> (2014) — are arguably more “psychological.”</p><p>This isn’t the most satisfying explanation either. Is it fair to call <em>Inception</em>, a film that is in many ways an action film, psychological but not <em>Oppenheimer </em>(2023), a film that explores the psychological effect of developing the atomic bomb on the titular character? I don’t think so.</p><p>Nevertheless, the evolution argument seems the most plausible to me. Nothing I’ve looked at “external” to Nolan (technology, personnel, industry standards) fully explains the change in Nolan’s style over his career. It seems Nolan has simply changed the way he frames faces because of a change in his visual preferences, changes which are likely personal in nature. Or perhaps it’s the combination of all these elements, that they all work in the same direction, pulling Nolan closer to his peers.</p><h3>Conclusion</h3><p>I think it’s fair to say that Christopher Nolan is a statistically exceptional director. This undermines the existing understanding of Nolan filmmaking style as, in Bordwell’s words, “a style without a style.” This is the inherent contradiction in Nolan: he uses extreme framings that don’t call attention to themselves. His “extreme” style is not about creating “unusual” compositions. Instead, he relentlessly centers his faces. This is why I refer to his style as <em>calculated transparency</em>. Contrary to some assumptions, he is not “transparent” because he tries to be “average.” His transparency is achieved by taking the baseline framings of contemporary Hollywood and turning it up to 11. The combined metrics of scale, density, and composition all point to one thing: Christopher Nolan’s framings are some of the most exceptional of all the directors in the sample.</p><p>I plan on doing more of these analyses of film directors. If you have a director you’d like to see me analyze, put them in the comments below.</p><h3>Appendix</h3><h4>Dispersion</h4><p>Dispersion measures how spread out the faces are across the screen. It’s calculated as follows:</p><pre>centers = df.groupby(&#39;imdb_id&#39;)[[&#39;center_x_norm&#39;, &#39;center_y_norm&#39;]].median()<br>df = df.join(centers, on=&#39;imdb_id&#39;, rsuffix=&#39;_med&#39;)<br>df[&#39;disp&#39;] = np.sqrt((df[&#39;center_x_norm&#39;] - df[&#39;center_x_norm_med&#39;])**2 + <br>                     (df[&#39;center_y_norm&#39;] - df[&#39;center_y_norm_med&#39;])**2)</pre><h4>Gini Score</h4><pre>def calculate_gini(array):<br>    &quot;&quot;&quot;Calculates Gini coefficient for a 1D array of cell distributions.&quot;&quot;&quot;<br>    # Ensure it&#39;s a numpy array and sort it<br>    cells = np.sort(array)<br>    n = len(cells)<br>        <br>    index = np.arange(1, n + 1)<br>    # Gini formula for a 3x3 grid (9 cells)<br>    return (np.sum((2 * index - n - 1) * cells)) / (n * np.sum(cells))</pre><h4>Rankings</h4><p>For this post, I re-watched all of Nolan’s films, so just for fun, I’ve decided to rank them. These rankings are purely subjective, so please don’t flame me.</p><ol><li><em>Memento </em>(2000)</li><li><em>Interstellar</em> (2014)</li><li><em>The Dark Knight </em>(2008)</li><li><em>Oppenheimer </em>(2023)</li><li><em>Dunkirk </em>(2017)</li><li><em>Following </em>(1998)</li><li><em>The Prestige </em>(2006)</li><li><em>Inception </em>(2010)</li><li><em>Batman Begins </em>(2005)</li><li><em>The Dark Knight Rises </em>(2012)</li><li><em>Insomnia </em>(2002)</li><li><em>Tenet </em>(2020)</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=07df959f924b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Shot Scale Across Film History]]></title>
            <link>https://medium.com/@amosstaileyyoung/shot-scale-across-film-history-40839b85e8a0?source=rss-d901c66b4ae7------2</link>
            <guid isPermaLink="false">https://medium.com/p/40839b85e8a0</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[movies]]></category>
            <dc:creator><![CDATA[Amos Stailey-Young]]></dc:creator>
            <pubDate>Thu, 08 Jan 2026 20:58:49 GMT</pubDate>
            <atom:updated>2026-05-01T15:27:19.128Z</atom:updated>
            <content:encoded><![CDATA[<h4>A Data Analysis Using CineFace</h4><p>I created the repository <a href="https://github.com/astaileyyoung/CineFace">CineFace</a> to serve as a database for facial data in film and television. In this post, I’ll see what the data can tell us about how shot scale has changed throughout American film history.</p><p>I’ve written about the subject <a href="https://medium.com/@amosstaileyyoung/identifying-shot-scale-with-artificial-intelligence-a273a225e44b">before</a>, but the picture has changed slightly since I’ve expanded the dataset. I won’t cover everything I wrote there, but there are a couple of things I want to touch on.</p><p>The premise behind this analysis is that the size of a face in the image correlates to “shot scale” (e.g., establishing shot, medium shot, close-up). There are strong theoretical reasons to make this assumption. The following quote from a canonical introductory textbook to film studies, <em>Film Art: An Introduction</em> by David Bordwell, Kristin Thompson, and Jeff Smith, is instructive:</p><blockquote>The framing of the image stations us relatively close to the subject or farther away. This aspect of framing is usually called camera distance. The terms for camera distance are approximate, and they’re usually derived from the scale of human bodies in the shot. Our examples are all from The Third Man. In the extreme long shot, the human figure is lost or tiny (5.106). This is the framing for landscapes, bird’s-eye views of cities, and other vistas. In the long shot, figures are more prominent but the background still dominates (5.107). Shots in which the human figure is framed from about the knees up are called medium long shots (5.108). These are common because they permit a nice balance of figure and surroundings. The medium shot frames the human body from the waist up (5.109). Gesture and expression now become more visible. The medium close-up frames the body from the chest up (5.110). The close-up is traditionally the shot showing just the head, hands, feet, or a small object. It emphasizes facial expression, the details of a gesture, or a significant object (5.111). The extreme close-up singles out a portion of the face or isolates and magnifies an object (5.112).</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/871/1*lMEXVUKP5hgOrTXXf9nrxw.png" /><figcaption>It seems my copy of Film Art has an error. I’m pretty sure figures 5.108 and 5.109 are reversed.</figcaption></figure><p>A note about the time frame: I’ve limited it to the period between 1915 and 1970 due to the availability of the films.</p><p>1915 marks the introduction of actual feature films, not just one- or two-reel shorts. The data from this period is problematic because a relatively high percentage of films is not simply unavailable — they are no longer in existence.</p><p>After 1970, I hit the problem of copyright — it’s simply harder to get films to analyze. Further, the films that are easily available for free tend to be low-quality, direct-to-video (DTV) releases. Ideally, I’ll be able to address these issues in the future.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JP36fcANRBi4M73RTh_m2g.png" /><figcaption>As you can see, the period between 1930 and 1960 is well-represented, but the number drops off significantly afterward. Since there are hundreds of movies made every year, having only, say, 30 movies results in high sampling error.</figcaption></figure><p>With those caveats out of the way, this is how relative face size changed between 1915 and 1970.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xH1f8M4GQTe20hN3ojoHLQ.png" /><figcaption>Top 1 only looks at the largest face in an image, ignoring all others.</figcaption></figure><p>There are two significant periods here: 1927–1930 and 1955–1970. The first corresponds to the introduction of sound, the second to the introduction of widescreen (and also the explosion in television viewership). The data tells us what happened but not why it happened. To know that, I’ll have to dive deeper into the data.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=40839b85e8a0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CineFace]]></title>
            <link>https://medium.com/@amosstaileyyoung/cineface-e760472ed2df?source=rss-d901c66b4ae7------2</link>
            <guid isPermaLink="false">https://medium.com/p/e760472ed2df</guid>
            <category><![CDATA[digital-humanities]]></category>
            <category><![CDATA[facial-recognition]]></category>
            <category><![CDATA[film]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Amos Stailey-Young]]></dc:creator>
            <pubDate>Sat, 21 Jun 2025 16:12:29 GMT</pubDate>
            <atom:updated>2025-06-21T16:12:29.408Z</atom:updated>
            <content:encoded><![CDATA[<h4>A Database for Faces in Movies and Television</h4><p><a href="https://github.com/astaileyyoung/CineFace">https://github.com/astaileyyoung/CineFace</a></p><p>The face is cinema’s most favored subject, a place where “the soul can be revealed,” as Ingrid Bergman thought. Understanding cinema requires us to interpret the meaning of the slightest gesture, to scrutinize a sudden twitch of an eyebrow or the almost imperceptible quiver of a lip. So when I was considering how to apply artificial intelligence to the study of cinema, it was hard to think of a more fitting subject than the human face.</p><p>The goal of CineFace is to provide a comprehensive database of identified faces in film and television. Doing so allows us to measure such things as character frequency (by title, year, genre, season, etc.) and face size (who gets the most close-ups, how has the frequency of close-ups changed over time, which directors prefer close-ups and which prefer longer shots, etc.). The data is available to download on my <a href="https://github.com/astaileyyoung/CineFace">GitHub</a>. It’s also available as a public dashboard, though it’s still in development.</p><p><a href="https://app.powerbi.com/view?r=eyJrIjoiMWE4YzViOWMtY2RiYy00ZTk1LWExNTgtMTg5YjZjNTE2NjIzIiwidCI6ImI3Yzk1YTkyLTBlYWQtNDRlOS04YjgzLTdjMGY5NmNiMDUyMSIsImMiOjF9">Power BI Report</a></p><p>CineFace uses facial detection and recognition to automatically tag images as belonging to a particular actor/character. It downloads headshots from TMDb and matches them to a detected face. It is built with Yolov11m for face detection and Facenet for encoding/matching, combining accurate detection with good performance. It relies on <a href="https://github.com/astaileyyoung/Visage">Visage</a> (written in C++ with hardware-accelerated decoding and high-performance inference using TensorRT) as a backend.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/990/1*DlS9PVKAVudJ-TDOfojFHQ.png" /><figcaption>Facial landmarks drawn with MediaPipe Face Mesh.</figcaption></figure><p>If you would like to analyze your own video files with CineFace, head over to the <a href="https://github.com/astaileyyoung/CineFace">GitHub</a> repository and download the code. I’ve tried to make the script as user-friendly as possible. Just follow the instructions in the Readme. In the future, I plan on setting up a way for users to submit their own results to the database.</p><p>CineFace is still in development, so expect updates detailing new features and changes. I also plan on writing a series of analyses using information from the database in the coming months. Since I’ve been working on this project for awhile, I may have forgotten to include some important details. If anyone has questions, leave a comment below.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e760472ed2df" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Large-Scale Facial Recognition with Qdrant Vector Database]]></title>
            <link>https://medium.com/@amosstaileyyoung/large-scale-facial-recognition-with-qdrant-vector-database-aa893f7e4a91?source=rss-d901c66b4ae7------2</link>
            <guid isPermaLink="false">https://medium.com/p/aa893f7e4a91</guid>
            <category><![CDATA[vector-database]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[facial-recognition]]></category>
            <dc:creator><![CDATA[Amos Stailey-Young]]></dc:creator>
            <pubDate>Thu, 06 Feb 2025 23:40:50 GMT</pubDate>
            <atom:updated>2025-02-06T23:40:50.038Z</atom:updated>
            <content:encoded><![CDATA[<p>Over the past decade, facial recognition has escaped the confines of world governments and big business to become a tool that almost anyone can use with just a few lines of code. Python libraries like <a href="https://github.com/serengil/deepface">DeepFace</a> have made facial recognition accessible to a wide range of users and applications. I’ve employed such tools for my project <a href="https://github.com/astaileyyoung/CineFace">CineFace</a>, which uses facial recognition to automatically identify actors in television and movies.</p><p>However, I quickly ran into a problem. Libraries like DeepFace become inefficient when scaling beyond a few hundred images. This is where vector databases become necessary. For my project, I chose to use the free vector database Qdrant, which can search thousands or even millions of vectors with lightning speed.</p><h4>How to Get Basic Facial Recognition Running</h4><p>The easiest way to do facial recognition in Python is with the DeepFace library, which provides a very user-friendly interface. With DeepFace, one can perform accurate and robust facial recognition in just a few lines of code. Comparing two faces to see if they belong to the same person requires only a simple function</p><pre>result = DeepFace.verify(<br>  img1_path = &quot;img1.jpg&quot;,<br>  img2_path = &quot;img2.jpg&quot;,<br>)</pre><p>And if one wants to identify who a face belongs to out of a list of images, all that is required is to run a single function that points to a directory containing the images one wants to match to</p><pre>dfs = DeepFace.find(<br>  img_path = &quot;img1.jpg&quot;,<br>  db_path = &quot;C:/workspace/my_db&quot;,<br>)</pre><p>This is all well and good as long as the “database” of images remains relatively small. For my project, however, I need to search through many thousands of images. At that scale, DeepFace’s inefficiencies become apparent (this isn’t really a deficiency of DeepFace; it acknowledges one “should combine DeepFace with a vector index or vector database”).</p><h4>How Does Facial Recognition Work?</h4><p>At root, facial recognition compares vectors and selects the most similar according to some metric (for reference, Qdrant supports four kinds of metrics: dot product, cosine similarity, Euclidean distance, and Manhattan distance). Vector similarity is not specific to facial recognition but is used in a wide variety of applications. Natural Language Processing (NLP), for instance, converts words and sentences into vectors, which can then be searched for in a similar manner.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/633/1*H8P2DfLNzWtfsK4I2lchRg.png" /><figcaption>An Illustration of how vector similarity works.</figcaption></figure><p>To use vector similarity in facial recognition, a face must first be converted into a vector. A two-dimensional detected face is fed into a Convolutional Neural Network, which outputs an n-dimensional vector whose size depends on the specific model selected. DeepFace supports the following models</p><pre>models = [<br>  &quot;VGG-Face&quot;, <br>  &quot;Facenet&quot;, <br>  &quot;Facenet512&quot;, <br>  &quot;OpenFace&quot;, <br>  &quot;DeepFace&quot;, <br>  &quot;DeepID&quot;, <br>  &quot;ArcFace&quot;, <br>  &quot;Dlib&quot;, <br>  &quot;SFace&quot;,<br>  &quot;GhostFaceNet&quot;<br>]</pre><p>The facial recognition model determines the shape of the vector, which then determines the shape of the vector database in Qdrant.</p><p>Qdrant server can be installed through docker</p><pre>docker pull qdrant/qdrant</pre><p>Then simply run Qdrant with</p><pre>docker run -p 6333:6333 qdrant/qdrant</pre><p>The Python client can simply be installed with pip</p><pre>pip install qdrant-client</pre><p>To load facial encodings into the Qdrant database, first create a collection, making sure to match the size of the selected facial encoding model (the model I’ve been using, Facenet, outputs a 128-dimensional vector)</p><pre>from qdrant_client import QdrantClient <br>from qdrant_client.models import Distance, VectorParams, PointStruct<br><br>CLIENT = QdrantClient(<br>  host=&#39;xxx.xxx.x.xxx&#39;, <br>  port=6333) # Replace &#39;host&#39; with network address  <br><br>CLIENT.recreate_collection(<br>  collection_name=&#39;FacialEmbeddings&#39;,<br>  vectors_config=VectorParams(size=128, distance=Distance.COSINE))</pre><pre>from pathlib import Path<br>from deepface import DeepFace<br><br>d = Path(&#39;path-to-images&#39;)<br>images = [x for x in d.iterdir()<br>encodings = [DeepFace.represent(x, model_name=&#39;name-of-model&#39;) for x in images]<br><br>points = []<br>for num, encoding in enumerate(encodings):<br>  # DeepFace returns a list of encodings for every face in each image.<br>  for n, e in enumerate(encoding):<br>    point = PointStruct(id=num+n,<br>                        payload={}, # Add metadata about the face/image here.<br>                        vector=e[&#39;embedding&#39;])<br>    points.append(point)<br>CLIENT.upsert(collection_name=&#39;FacialEmbeddings&#39;,<br>              points=points)<br>  </pre><p>Once the facial encodings have been successfully uploaded to the Qdrant database, one can now search through thousands or even millions of faces in mere milliseconds. In contrast, only using DeepFace means that the directory containing the database of images must be scanned, each image loaded into memory, then perform face detection on that image, followed by facial alignment and encoding, before the vectors are finally compared to one another.</p><pre>target_encoding = DeepFace.represent(&#39;path-to-image&#39;,<br>                                     model=&#39;name-of-model&#39;)<br>response = CLIENT.query_points(collection_name=&#39;FacialEmbeddings&#39;,<br>                               query=target_encoding[0][&#39;embedding&#39;],<br>                               limit=10)</pre><p>Qdrant returns a list of points in order of similarity score. For facial recognition, we are simply looking for the most similar, so we can simply take the first result. There are more complex ways of searching for points, including filtering by various conditions, which can be explored in the Qdrant documentation <a href="https://qdrant.tech/documentation/">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aa893f7e4a91" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cinemetrics]]></title>
            <link>https://medium.com/@amosstaileyyoung/cinemetrics-0feb83728b65?source=rss-d901c66b4ae7------2</link>
            <guid isPermaLink="false">https://medium.com/p/0feb83728b65</guid>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[film]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[dashboard]]></category>
            <dc:creator><![CDATA[Amos Stailey-Young]]></dc:creator>
            <pubDate>Wed, 04 Dec 2024 22:20:14 GMT</pubDate>
            <atom:updated>2024-12-04T22:20:14.322Z</atom:updated>
            <content:encoded><![CDATA[<p>Visualizing Shots in Movies</p><p><a href="https://app.powerbi.com/view?r=eyJrIjoiOTQ3YTI0YjAtYzU1Yy00MGE2LWIzNTItM2MzMjkwMjIzM2EzIiwidCI6ImI3Yzk1YTkyLTBlYWQtNDRlOS04YjgzLTdjMGY5NmNiMDUyMSIsImMiOjF9">Link to Dashboard.</a></p><p>The “shot” is cinema’s fundamental building block, which makes shot data indispensable when performing film analysis. So it makes sense that when film scholars first tried to measure and analyze movies, they started by counting shots.</p><p>The problem, however, is that computers aren’t very good at recognizing where one shot ends and another begins, at least not yet. While fairly good with straight cuts, shot boundary detection fails badly when identifying gradual transitions (e.g., dissolves). This means a person has to physically watch the film and tediously count the shots by hand. Not terribly efficient.</p><p>To avoid duplicating this effort, film scholars created Cinemetrics, a database where everyone can share their shot counts. While Cinemetrics is a fantastic resource, it presents the data as a giant table of numbers, which isn’t very easy to explore and understand. That’s why I built a dashboard to make this valuable data more accessible and visually engaging.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iPMmESslHkxSm2J7JNK-Cg.png" /></figure><p>With the dashboard, you can visualize the data by different measures, such as average shot length (ASL), median shot length (MSL), and standard deviation (STD). Further, you can group by various categories, such as title, year, director, etc. You can slice the data in different ways as well. If you only want to look at the films of, say, John Ford that’s no problem.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iAuoT7VOH03RCVIFwPITOA.png" /><figcaption>You can search for any director (or genre, country, and producer) in the database and view only their films.</figcaption></figure><p>There are some major caveats to this dashboard, however, mostly because of problems with the underlying data. The main issue with the Cinemetrics database is the data quality which, to put it mildly, is poor. There are no limitations on what users can enter into the database, so we end up with a lot of missing fields and improperly entered data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PyNxGgvFN4G6rhUmpz2pDg.png" /><figcaption>A snippet from the most recently entered data on Cinemetrics. Notice the many entries that lack even the most basic identifying information. Unfortunately, such entries are all too common.</figcaption></figure><p>I had to perform a lot of data manipulation to make the dashboard function. However, rather than trying to clean all the data, which could take forever, I decided on a different approach. I used the title and year fields as best I could to match entries to their equivalent IMDb IDs. Then, using the IMDb ID, I pulled the appropriate metadata for the entries using the IMDb API.</p><p>This had several benefits over traditional text cleaning. For one, it was much faster since I could ignore fields other than title and year. Secondly, there are many cases where an entry in the Cinemetrics database only has a title or maybe a year and lacks information on the director, producer, country, etc. Pulling information from IMDb resulted in having significantly more metadata on the entries than previously.</p><p>The downside of this method is that I had to toss any entry for which I could not locate an IMDb ID. However, many of these entries were fairly useless anyway since they often didn’t even have enough data to be identified manually.</p><p>Cinemetrics provides users with a custom tool to make counting shots much easier. This tool captures much more information than simply counting the shots. Additionally, capturing timecode data means that the shots in the film can be visualized.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1013/1*wM5h3iE-oqXKY8GOkcraCg.png" /><figcaption>Advanced information is available for certain entries that used the Cinemetrics Measurement Tool.</figcaption></figure><p>I’ve partially recreated this in my dashboard as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Zxc_bGFpafx0G9f2FI-gmw.png" /></figure><p>If anyone has any thoughts on features to add or whatnot, let me know in the comments or head over to the <a href="https://github.com/astaileyyoung/CinemetricsFilmSample">GitHub </a>page. Again, the dashboard can be found <a href="https://app.powerbi.com/view?r=eyJrIjoiOTQ3YTI0YjAtYzU1Yy00MGE2LWIzNTItM2MzMjkwMjIzM2EzIiwidCI6ImI3Yzk1YTkyLTBlYWQtNDRlOS04YjgzLTdjMGY5NmNiMDUyMSIsImMiOjF9">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0feb83728b65" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Clustering Faces with Python]]></title>
            <link>https://medium.com/pythons-gurus/clustering-faces-with-python-aef799514cd8?source=rss-d901c66b4ae7------2</link>
            <guid isPermaLink="false">https://medium.com/p/aef799514cd8</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[clustering]]></category>
            <category><![CDATA[artficial-intelligence]]></category>
            <category><![CDATA[facial-recognition]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Amos Stailey-Young]]></dc:creator>
            <pubDate>Fri, 26 Jul 2024 22:38:39 GMT</pubDate>
            <atom:updated>2024-07-29T12:27:01.743Z</atom:updated>
            <content:encoded><![CDATA[<h4>PCA, TSNE, DBSCAN, HDBSCAN, and Chinese Whispers</h4><p>A while back, I was watching the TV show <em>Homeland </em>(2011) and noticed the frequency of close-ups given to the character of Nicholas Brody (played by Damien Lewis). Without giving too much away, Brody, a POW returning from captivity in Afghanistan, may have been compromised by terrorists, which he must (presumably) hide from his friends, family, and the government. Much of the show hinges on this ambiguity: is he a terrorist or not? My theory, then, was that the show gives a lot of close-ups to this character because it puts us in the same position as the CIA agents: scrutinizing his every gesture, expression, and tick for the slightest indication of deception.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/608/1*BQ58IDAGWSgRV9jWx8kkHw.png" /><figcaption>Typical of the tight close-ups given to the character of Nicholas Brody (played by Damien Lewis).</figcaption></figure><p>How to test this theory, though? Essentially, I’d have to measure the face size of each person in the image and compare their sizes against each other. However, I’d also have to identify a particular face as belonging to an individual character. Doing this by hand would take an eternity, so I looked to automatic methods: this is where face detection and facial recognition come into play.</p><p>Detecting faces in the image is relatively easy with modern AI. There are numerous face detection libraries, such as Face Recognition and DeepFace, that can easily do this (as long as one knows Python). It’s in identifying who the faces belong to that things start to get tricky.</p><p>Face recognition requires comparing an unknown face to a known one. But how do we identify a face when we don’t know who we’re looking for? That’s where clustering comes in.</p><p>Clustering algorithms present mathematical methods to group data into “clusters” automatically. In contrast to <em>supervised</em> machine learning methods like LLMs (e.g., ChatGPT), clustering is an example of <em>unsupervised </em>learning. Supervised AI models require both a <em>training </em>and a <em>testing </em>dataset, datasets that humans must annotate manually. Whenever such a dataset is unavailable, <em>unsupervised </em>methods like clustering become useful.</p><h4>Detecting Faces</h4><p>Clustering faces requires two preparatory stages: detection and encoding. Thankfully, we can leverage existing pre-trained face detectors. I used Python’s <a href="https://github.com/ageitgey/face_recognition">Face Recognition</a> module — a wrapper for the powerful <a href="https://github.com/davisking/dlib">Dlib</a> face recognition library — because of its simplicity.</p><p>To install Face Recognition, just use Python’s pip (note that if you don’t have a GPU with CUDA support, Face Recognition cannot use its CNN “deep learning” method for detection)</p><pre>pip install face_recognition</pre><p>After installing the package, we can use it in the following way</p><pre>import face_recognition<br><br>img = face_recognition.load_image_file(&quot;example_path.png&quot;)<br>face_locations = face_recognition.face_locations(img)</pre><p>If there are multiple faces in the image, the script will, hopefully, detect all of them and return them as a list of coordinates. We can use these coordinates to locate the face within the image.</p><pre>from io import BytesIO<br><br>import cv2<br>import requests<br>import numpy as np<br>import face_recognition<br>from PIL import Image<br><br><br>def draw_faces(raw,<br>               boxes,<br>               width=2):<br>  img = np.array(raw.convert(&#39;RGB&#39;))<br>  for box in boxes:<br>    top, right, bottom, left = box<br>    cv2.rectangle(img, (left, top), (right, bottom), (255, 0, 0), width)<br>  img_pil = Image.fromarray(img)<br>  return img_pil<br><br>src = &#39;https://github.com/astaileyyoung/FaceScaleFilmSample/blob/main/memories_of_murder_example.png?raw=true&#39;<br>response = requests.get(src)<br>raw = Image.open(BytesIO(response.content))<br>faces = face_recognition.face_locations(np.array(raw.convert(&#39;RGB&#39;)))<br>img_pil = draw_faces(raw,<br>                     faces,<br>                     width=15)<br>display(img_pil.resize((int(w/3), int(h/3)), Image.LANCZOS))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0l5uhlkVQWDiIolN2WGVWQ.jpeg" /></figure><p>I then iterated over every 24th frame of each episode of <em>Homeland </em>and ran face detection over each image.</p><h4>Encoding the Faces</h4><p>Okay, so we’re able to locate a face within an image. After grabbing a bunch of faces, how do we cluster them? Clustering is a mathematical process that measures the distance between points and tries to minimize that distance. Raw image data cannot be clustered because the pixel values are too arbitrary. Before we can cluster the faces, we must “encode” them. Encoding (or “embedding”) a face means converting an image to a vector using a neural net, which in this case is provided by dlib (through Face Recognition).</p><pre>face_encoding = face_recognition.face_encodings(image)</pre><p>The result is simply a list of 128 values</p><p>0.09047424793243408, 0.08664017170667648, 0.0335666760802269, -0.059589020907878876, -0.18262404203414917, -0.007828116416931152, -0.01254921406507492, -0.140171080827713, 0.23978763818740845, -0.07371924817562103, 0.16542261838912964, 0.027734586969017982, -0.32178592681884766, 0.03149281442165375, -0.06373660266399384, 0.09331502765417099, -0.05042200908064842, -0.16968876123428345, -0.14314332604408264, -0.04921616613864899, 0.03222231566905975, -0.019702844321727753, 0.02465391904115677, 0.05331072211265564, -0.1401691436767578, -0.192920982837677, -0.08213967829942703, -0.07414095103740692, -0.03477153182029724, -0.109731525182724, 0.017493093386292458, 0.11840774863958359, -0.14151352643966675, -0.02279588207602501, 0.017042215913534164, 0.05014650523662567, -0.019179368391633034, -0.10313141345977783, 0.2309148758649826, -0.13363827764987946, -0.21679207682609558, 0.0067617036402225494, 0.05983930826187134, 0.1411661058664322, 0.23589865863323212, -0.03552208095788956, 0.0541427917778492, -0.10796893388032913, 0.16243751347064972, -0.3348241150379181, 0.06379354000091553, 0.15678948163986206, 0.03698333352804184, 0.04511084780097008, 0.10900081694126129, -0.2327529639005661, -0.062011636793613434, 0.18904082477092743, -0.1810474395751953, 0.08518259227275848, 0.04126887768507004, -0.13194988667964935, -0.10573568940162659, -0.17083215713500977, 0.19515511393547058, 0.1456204652786255, -0.1836267113685608, -0.17355471849441528, 0.2255847454071045, -0.21043679118156433, -0.02270231395959854, 0.1550682783126831, -0.1214054748415947, -0.20011673867702484, -0.2315644472837448, 0.054918885231018066, 0.4290865957736969, 0.14757253229618073, -0.13114121556282043, 0.09007684886455536, -0.12104616314172745, -0.024741927161812782, -0.13579991459846497, 0.03729991987347603, -0.010648693889379501, -0.06406402587890625, -0.08977516740560532, -0.009953752160072327, 0.2665223777294159, -0.0250614695250988, 0.019066106528043747, 0.30797499418258667, 0.021504895761609077, -0.0209052674472332, -0.02292865328490734, 0.10661065578460693, -0.06970414519309998, -0.0738951563835144, -0.08496291935443878, 0.07094280421733856, -0.028537951409816742, -0.13717380166053772, -0.01813361793756485, 0.051032859832048416, -0.14245373010635376, 0.12496335059404373, -0.08696043491363525, 0.04684065282344818, -0.06836427748203278, -0.08096832036972046, -0.0669078677892685, 0.014456257224082947, 0.2083589881658554, -0.3620230257511139, 0.2104438841342926, 0.06390407681465149, 0.04417821764945984, 0.14623413980007172, 0.00010270532220602036, 0.12411552667617798, 0.06947408616542816, -0.03792853653430939, -0.13580386340618134, -0.11984572559595108, 0.05200983211398125, -0.07869939506053925, -0.015061482787132263, 0.1188763678073883</p><p>These encodings are what we will be clustering.</p><h3>Clustering the Faces</h3><p>The data from this project (in the form of a csv) can be downloaded from <a href="https://media.githubusercontent.com/media/astaileyyoung/FacesOfHomeland/main/data/faces.csv?token=AEAKQAZOEPOWNTY4M3PWHXDGQH2A6">here</a>. Or you can use this command</p><pre>wget https://github.com/astaileyyoung/FacesOfHomeland/blob/main/data/faces.csv</pre><p>Load the data with Pandas and parse the facial embeddings. The embeddings must be stored as strings when saved as a csv, so we need to convert them back to arrays.</p><pre>import pandas <br><br>df = pd.read_csv(&#39;faces.csv&#39;, index_col=0)<br>x = np.array([np.array(ast.literal_eval(x)) for x in df[&#39;encoding&#39;].tolist()])</pre><p>Once we have all the vectors loaded, it’s time to start clustering.</p><h4>PCA</h4><p>Principal Component Analysis (PCA) is a “dimensionality reduction” technique that attempts to preserve the features most relevant to the data. It’s often used as a preprocessing step in clustering to speed up the process, but it also allows us to take the 1 x 128 vectors and convert them to two dimensions which means we can plot the faces visually.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C6F6-hLswxAn90rydija2w.png" /></figure><p>Even just using PCA sort of groups the faces together, which makes it easier for the clustering algorithms.</p><h4><strong>KMeans</strong></h4><p>KMeans is one of the simplest clustering algorithms, but its main drawback is that it requires knowing the number of clusters ahead of time. Fortunately, we can use IMDb to get the number of actors within an episode of a TV show to get the number of clusters. However, some of these clusters will have minuscule sample sizes, which can cause issues. It probably still requires manual effort to decide which characters are “significant” enough to warrant a cluster.</p><p>The results of KMeans were worthless, regardless of how many clusters I specified. The distribution of the data does not seem conducive to KMeans, which prefers uniform (or “isotropic”) and circular (“convex”) distributions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ehAL1Iko66aSAKHsukZ7JQ.png" /><figcaption>While similar faces are adjacent to one another, the groups are not “circular” in shape, which makes using KMeans inappropriate.</figcaption></figure><p>KMeans tries to minimize the distance between points and the “centroid” within a cluster, but the faces above aren’t grouped into consistent, circular shapes. We’ll have to try the “density”-based approaches of other clustering algorithms.</p><h4>TSNE</h4><p>T-Distributed Stochastic Neighbor Embedding (t-SNE) is not strictly a clustering algorithm but a method for visualizing high-dimensional data. I can’t pretend to understand the math behind it, but as scikit-learn explains, “t-SNE is a tool to visualize high-dimensional data. It converts similarities between data points to joint probabilities and tries to minimize the Kullback-Leibler divergence between the joint probabilities of the low-dimensional embedding and the high-dimensional data.” t-SNE was quite successful at “clustering” the faces together, as seen below.</p><pre>pca_x = PCA().fit_transform(x)<br>tsne = TSNE(perplexity=50,<br>            n_components=2,<br>            learning_rate=75,<br>            n_iter=1000,<br>            early_exaggeration=12,<br>            n_iter_without_progress=300<br>         )<br>tsne_x = tsne.fit_transform(pca_x)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*knyTyUWBqvpkU-ZZxuuhJw.png" /><figcaption>t-SNE is fairly successful at grouping similar faces, but the actual clustering would have to be performed manually.</figcaption></figure><p>While t-SNE visually separates the data, it cannot actually identify clusters. However, in my experimentation, using t-SNE first as a sort of preprocessing state greatly improved the performance of the clustering algorithms.</p><p>One of the issues with t-SNE is its sensitivity to hyperparameters, which is also an issue with clustering. For instance, witness the results when changing the single parameter of “perplexity” from 50 to 10.</p><pre>tsne = TSNE(perplexity=10,<br>            n_components=2,<br>            learning_rate=75,<br>            n_iter=1000,<br>            early_exaggeration=12,<br>            n_iter_without_progress=300<br>         )<br>tsne_x = tsne.fit_transform(pca_x)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LPXK9R3wTheEqjYbHl-poA.png" /><figcaption>Changing hyperparameters can have drastic effects on the results.</figcaption></figure><p>Trial-and-error seems to be the only way to select the right parameters, and different datasets will require different parameters. I tried the same parameters with other face data and the results were not nearly as good. The significance of hyperparameters is a common problem with unsupervised learning methods.</p><h4>DBSCAN</h4><p>Density-Based Spatial Clustering of Applications with Noise is a clustering method that “finds core samples of high density and expands clusters from them.” The benefit of density clustering methods is that we don’t need to know the number of clusters ahead of time, unlike methods such as KMeans. Combined with t-SNE, DBSCAN was pretty successful at correctly clustering the faces.</p><pre>def get_clusters(data, algorithm, *args, **kwds):<br>    labels = algorithm(*args, **kwds).fit_predict(data)<br>    palette = sns.color_palette(&#39;deep&#39;, np.max(labels) + 1)<br>    colors = [palette[x] if x &gt;= 0 else (0,0,0) for x in labels]<br>    return labels, colors<br><br>labels, colors = get_clusters(tsne_x, cluster.DBSCAN, n_jobs=-1, eps=4, min_samples=15)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t6R-EehXf8DVgezJhBfloQ.png" /></figure><p>Like t-SNE, DBSCAN is sensitive to hyperparameters, particularly the “eps” parameter. Changing the value from 0.5 to 0.4, for instance, results in the number of clusters increasing from 9 to 14.</p><h4>HDBSCAN</h4><p>Hierarchical Density-Based Spatial Clustering of Applications with Noise (HDBSCAN) is a version of DBSCAN that “performs <a href="https://scikit-learn.org/stable/modules/generated/sklearn.cluster.DBSCAN.html#sklearn.cluster.DBSCAN"><strong>DBSCAN</strong></a> over varying epsilon values and integrates the result to find a clustering that gives the best stability over epsilon. This allows HDBSCAN to find clusters of varying densities (unlike <a href="https://scikit-learn.org/stable/modules/generated/sklearn.cluster.DBSCAN.html#sklearn.cluster.DBSCAN"><strong>DBSCAN</strong></a>), and be more robust to parameter selection.” Despite this description, HDBSCAN could not deliver better results than DBSCAN, even after I tinkered extensively with the parameters.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qgYTlVAbfBLFEiqTgmGvJQ.png" /></figure><h4>Other Density-Based Techniques</h4><p>There are various other clustering algorithms (the results for each method are below), but none performed as well as DBSCAN.</p><h4>Agglomerative Clustering</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*alRdylH5mBj9sLjK4iDHcw.png" /></figure><h4>Birch Clustering</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QNo0r67ygVkhaYy51hafHA.png" /></figure><h4>Birch + Agglomerative Clustering</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x5tD7oaK5ui1Xz19r_VdlA.png" /></figure><p>For whatever reason, using Birch clustering before Agglomerative clustering produces promising results. If I had more time, I might have compared Birch+Agglomerative clustering to DBSCAN.</p><p>I attempted a few other methods, such as OPTICS (Ordering Points To Identify the Clustering Structure), Spectral Clustering, and Affinity Propagation, but ultimately DBSCAN provided the best results with the least complexity of the density-based methods.</p><h4>Chinese Whisper</h4><p>There are other clustering methods based on a network approach, in particular the Chinese Whispers algorithm. For reasons I don’t quite understand, the Chinese Whispers method is used infrequently. Its Wikipedia entry is scant compared to DBSCAN and few articles are written about it. Not only did I find Chinese Whispers to be quite accurate, but it’s also pretty fast. Further, Chinese Whispers is not as sensitive to hyperparameters as the other clustering algorithms. This makes it much more suitable for my eventual goal of automation.</p><p>It was not possible to visually establish whether DBSCAN or Chinese Whispers was more accurate, so I sampled the results for comparison. I took about 350 images from each algorithm to see if they were correctly clustered.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/1*by0s2-g_ir1K9-ImtTaCnQ.png" /></figure><p>Chinese Whispers performed a lot better than DBSCAN. While 65% accuracy for a multi-label classification problem is not horrible, it’s obviously not ideal. Chinese Whispers not only performed better, but it also required much less tinkering with hyperparameters. The only hyperparameter in dlib’s implementation is the threshold, which I left at the default value of 0.5.</p><h4>Initial Results</h4><p>A quick review of the data lends some (though not much) support to my hypothesis that Nicholas Brody receives more close-ups than others, though more research is needed to conclude that with any confidence.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/1*hdzpcfhEATMYBwVTyIMo3g.png" /><figcaption>Boxplots for the characters who most frequently appear in Season 1 of Homeland (2011).</figcaption></figure><p>With the exception of the minor character of Aileen Morgan — who has an oddly high average — Nicholas Brody does have the highest average face size (6.4%). However, it’s not radically more than Saul Berenson (6.1%) or Carrie Matheson (5.3%). Although Brody’s average is not substantially higher than other characters, there are a number of outliers that might account for the sense that he receives more close-ups. I’ll examine the data in more detail in a later post.</p><h3>Conclusion</h3><p>Although it’s not as well known as DBSCAN, the Chinese Whispers algorithm worked the best of all the clustering methods I tried. Not only was Chinese Whispers the most accurate, but it was also the simplest to use as it didn’t require any preprocessing steps or fiddling with hyperparameters. This simplicity of use is quite important to me because I plan on automating the process as much as possible, which would allow me to scale and look at other TV series. DBSCAN required too much tinkering with hyperparameters to work for such a purpose.</p><p>For this project, I had to manually identify which clusters represented which characters. My next post will explore how to automate this process using facial recognition.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aef799514cd8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/pythons-gurus/clustering-faces-with-python-aef799514cd8">Clustering Faces with Python</a> was originally published in <a href="https://medium.com/pythons-gurus">Python’s Gurus</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What’s the Best Face Detector?]]></title>
            <link>https://medium.com/pythons-gurus/what-is-the-best-face-detector-ab650d8c1225?source=rss-d901c66b4ae7------2</link>
            <guid isPermaLink="false">https://medium.com/p/ab650d8c1225</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Amos Stailey-Young]]></dc:creator>
            <pubDate>Sun, 09 Jun 2024 16:41:22 GMT</pubDate>
            <atom:updated>2026-03-05T19:34:41.846Z</atom:updated>
            <content:encoded><![CDATA[<h4>Comparing Dlib, OpenCV DNN, Yunet, Pytorch-MTCNN, and RetinaFace</h4><p>For a facial recognition problem I’m working on, I needed to figure out which facial detection model to select. Face detection is the first part of the facial recognition pipeline, and it’s critical that the detector accurately identifies faces in the image. Garbage in, garbage out, after all.</p><p>However, the myriad options available left me feeling overwhelmed, and the scattered writings on the subject weren’t detailed enough to help me decide on a model. Comparing the various models took a lot of work, so I figured relaying my research may help folk in similar situations.</p><h3>What to Look for in a Face Detector?</h3><p>The primary trade-off when selecting a facial detection model is that between accuracy and performance. But there are other factors to consider.</p><p>Most of the articles on face detection models are written either by the creators of the model — typically in journals — or by those implementing the model in code. In both cases, the writers, naturally, have a bias toward the model they are writing about. In some extreme cases, they are essentially promotional advertisements for the model in question.</p><p>There aren’t many articles that compare how the different models perform against each other. Adding further confusion, whenever someone is writing about a model such as RetinaFace, they are talking about a particular <em>implementation</em> of that model. The “model” itself is really the neural network <em>architecture, </em>and different implementations of the same network architecture can lead to different results. To make matters more complicated, the performance of these models also differs according to post-processing parameters, such as confidence thresholds, non-maximum suppression, etc.</p><p>Every writer casts their model as the “best”, but I quickly realized that “best” depends on context. There is no objective best model. There are two main criteria when deciding which face detection model is most appropriate for the given context: accuracy and speed.</p><p>No model combines high accuracy with high speed; it’s a trade-off. We also have to look at metrics beyond raw accuracy, on which most benchmarks are based (correct guesses / total sample size), but raw accuracy is not the only metric to pay attention to. The ratio of false positives to true positives, and false negatives to true negatives, is also an important consideration. In technical terms, the trade-off is between <em>precision (</em>minimizing <em>false positives</em>) and <em>recall (</em>minimizing<em> false negatives). </em><a href="https://www.analyticsvidhya.com/blog/2020/09/precision-recall-machine-learning/#:~:text=actual%20spam%20emails.-,Choosing%20between%20Precision%20and%20Recall%3A,false%20positives%20(unnecessary%20tests).">This article</a> discusses the problem in more depth.</p><h3>Testing the Models</h3><p>There are a few existing face detection datasets used for benchmarking, such as <a href="http://shuoyang1213.me/WIDERFACE/WiderFace_Results.html">WIDER FACE</a>, but I always like to see how the models will perform on my own data. So I randomly grabbed 1064 frames from my sample of TV shows to test the models ( ±3% margin of error). When manually annotating each image, I tried to select as many faces as possible, including faces that were partially or almost fully occluded to give the models a real challenge. Because I’m eventually going to perform facial recognition on the detected faces, I wanted to test the limits of each model.</p><p>The<a href="https://huggingface.co/datasets/astaileyyoung/FaceDetectionSample/blob/main/images.zip"> images</a> are available to download with their <a href="https://huggingface.co/datasets/astaileyyoung/FaceDetectionSample/blob/main/annotations.ndjson">annotations</a>.</p><p>It helps to group the various models into two camps; those that run on the GPU and those that run on the CPU. In general, if you have a CUDA-compatible GPU, you should use a GPU-based model. I have an NVIDIA 1080 TI with 11GB of memory, which allows me to use some of the larger-scale models. Nevertheless, the scale of my project is huge (I’m talking thousands of video files), so the lightning-fast CPU-based models intrigued me. There aren’t many CPU-based face detection models, so I decided to test only the most popular one: YuNet. Because of its speed, YuNet forms my baseline comparison. A GPU model must be significantly more accurate than its CPU counterpart to justify its slower processing speed.</p><h3>The CPU Model</h3><h4>YuNet</h4><p>YuNet was developed with performance in mind with a model size that is only a fraction of the larger models. For instance, YuNet has only 75,856 parameters compared to the 27,293,600 that RetinaFace boasts, which allows YuNet to run on “edge” computing devices that aren’t powerful enough for the larger models.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T4f207IYEOtPKsjDPRwcNA.png" /><figcaption>Wu, W., Peng, H. &amp; Yu, S. YuNet: A Tiny Millisecond-level Face Detector. <em>Mach. Intell. Res.</em> <strong>20</strong>, 656–665 (2023). <a href="https://doi.org/10.1007/s11633-023-1423-y">https://doi.org/10.1007/s11633-023-1423-y</a></figcaption></figure><p>Code to implement the YuNet model can be found in this <a href="https://github.com/ShiqiYu/libfacedetection">repository</a>. The easiest way to get YuNet up and running is through OpenCV.</p><pre>cv2.FaceDetectorYN_create(&#39;./face_detection_yunet_2023mar.onnx&#39;,<br>                          &quot;&quot;, <br>                          (300, 300),<br>                          score_threshold=0.5) </pre><p>The pre-trained model is available at the OpenCV Zoo repository <a href="https://github.com/opencv/opencv_zoo">here</a>. Just be sure when cloning the repo to use Git LFS (I made that mistake at first). There’s a Google Colab file I wrote to demonstrate available <a href="https://drive.google.com/file/d/1_uOdesvdnDLG8fZAMJKqbTNrlbxgdUD0/view?usp=sharing">here</a>.</p><p>YuNet performed a lot better than I expected for a CPU model. It’s able to detect large faces without a problem but does struggle a bit with smaller ones.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6qoMrdn_VzLaeTC_TZT3rw.jpeg" /><figcaption>Able to detect large faces even when at oblique angles. The bounding box is a bit off, possibly because the image needs to be resized to 300x300 to feed into the model.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/885/1*BUy6fpmCv7g6IHQbmArBuA.jpeg" /><figcaption>YuNet manages to find almost all of the faces but includes some false positives as well.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y4QUOOYHwpgVrFsWDxuOcg.png" /></figure><p>The accuracy improves greatly when limiting to the largest face in the image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xDaMhUcL9iJeLseZS3FXbQ.png" /></figure><p>If performance is a primary concern, YuNet is a great option. It’s even fast enough for real-time applications, unlike the GPU options available (at least without some serious hardware).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GXxrCQodjT45UVbiDbY9gQ.png" /><figcaption>YuNet uses a fixed input size of 300x300, so the time difference results from resizing the images to these dimensions.</figcaption></figure><h3>The GPU Models</h3><h4>Dlib</h4><p>Dlib is a C++-implementation with a Python wrapper that maintains a balance between accuracy, performance, and convenience. Dlib can be installed directly through Python or accessed through the <a href="https://github.com/ageitgey/face_recognition">Face Recognition</a> Python library. However, there is a very strong trade-off between Dlib accuracy and performance based on the <em>upsampling</em> parameter. When the number of times to upsample is set to 0, the model is faster but less accurate.</p><h4>No Upsampling</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2CC4hHTvLzC1OPSb-Z1_lA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FJLhfvJRIa-ZiQYZwbwxYw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NBgAWGE6rlXi55kPH_e-7Q.png" /></figure><h4>Upsampling = 1</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*byjy63V4-4K9r1Brdxg6Tw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yel_ua30AYkMkwPsjuMSqg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QMlQeg9xmshwmecQjt2Jcw.png" /></figure><p>The accuracy of the Dlib model increases with further upsampling, but anything higher than upsampling=1 would cause my script to crash because it exceeded my GPU memory (which is 11GB by the way).</p><p>Dlib’s accuracy was somewhat disappointing relative to its (lack of) speed. However, it was very good at minimizing false positives, which is a priority of mine. Face detection is the first part of my facial recognition pipeline, so minimizing the number of false positives will help reduce errors downstream. To reduce the number of false positives even further, we can use Dlib’s confidence output to filter lower-confident samples.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pPcXwPLbFyaUlsgzNk76uQ.png" /></figure><p>There is a large discrepancy in confidence between false and true positives, which we can use to filter out the former. Rather than choose an arbitrary threshold, we can look at the distribution of confidence scores to select a more precise one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BtCACXpCARcWT9oMs0IFGg.png" /></figure><p>95% of the confidence values fall above 0.78, so excluding everything below that value reduces the number of false positives by half.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s9Gr_6JgevEYwXOVRv1NAg.png" /></figure><p>While filtering by confidence reduces the number of false positives, it does not increase the overall accuracy. I would consider using Dlib when minimizing the number of false positives is a primary concern. But otherwise, Dlib doesn’t offer a large enough increase in accuracy over YuNet to justify the much higher processing times; at least for my purposes.</p><h4>OpenCV DNN</h4><p>The primary draw of OpenCV’s face detection model is its speed. However, its accuracy left something to be desired. While it is incredibly fast when compared to the other GPU models, even its Top 1 accuracy was hardly better than YuNet’s overall accuracy. It’s unclear to me in which situation I would ever choose the OpenCV model for face detection, especially since it can be tricky to get working (you have to build OpenCV from source, which I’ve written about <a href="https://medium.com/@amosstaileyyoung/build-opencv-with-dnn-and-cuda-for-gpu-accelerated-face-detection-27a3cdc7e9ce">here</a>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*II-jIZDhpj0Q8NI-lk_6aQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EmsQzxaMJthshiwFREIySQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yljMG_4Ecj9HJnVAfN9gFA.png" /></figure><h4>Pytorch-MCNN</h4><p>The MTCNN model also performed quite poorly. Although it was slightly more accurate than the OpenCV model, it was quite a bit slower. Since its accuracy was lower than YuNet, there was no compelling reason to select MTCNN.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QY5lFG2qN6-r1gqP0eXNoA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YKw0OWcJm2toZ0bVqH5xVA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iryRJORMobVx8eWOqAV-2Q.png" /></figure><h4>RetinaFace</h4><p>RetinaFace has a reputation for being the most accurate of open-source face detection models. The test results back up that reputation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BzFZtszwf1_EYzIDGpReZQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5nUYdg_Yq2TaMhU_2F3W5g.png" /></figure><p>Not only was it the most accurate model, but many of the “inaccuracies” were not, in fact, actual errors. RetinaFace really tested the category of “false positive” since it picked up faces I hadn’t seen, hadn’t bothered to annotate because I thought them too difficult, or hadn’t even considered a “face.”</p><p>It picked up a partial face in a mirror in this Seinfeld frame.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ejLJQJGKFlw2R18oMvL6WA.png" /></figure><p>It managed to locate faces in picture frames in the background of this Modern Family.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fTPNdUP07rJDmeV6pDEQug.png" /></figure><p>And it’s so good at identifying “faces,” that it finds non-human ones.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0PY2X71KV6dKdPcmRkoozA.png" /></figure><p>It was a nice surprise learning that RetinaFace wasn’t all that slow either. While it wasn’t as fast as YuNet or OpenCV, it was comparable to MTCNN. While it is slower at lower resolutions than MTCNN, it scales relatively well and can process higher resolutions just as quickly. And RetinaFace beat Dlib (at least when having to upscale). It is much slower than YuNet but is significantly more accurate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NhrGsIFydQAWk7DomrkUcg.png" /></figure><p>Many of the “false positives” RetinaFace identified can be excluded by filtering out smaller faces. If we drop the lowest quartile of faces, the false positive rate drops drastically.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cybsFsPSQtr6ygbWo2FK3Q.png" /><figcaption>The boundary for the lowest quartile is 0.0035</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y325MbXzSkVj9Js1PxtqVQ.png" /></figure><p>While RetinaFace is incredibly accurate, the errors do have a particular bias. Although RetinaFace identifies small faces with ease, it struggles with larger, partially occluded ones, which is evident if we look at face size relative to accuracy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9c0AyiB3Al_sDmASonEanw.png" /></figure><p>This could be problematic for my purposes since the size of a face in an image is strongly correlated to its importance. Therefore, RetinaFace may miss the most important cases, such as the example below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O4mMVdyCNI5AjdTnvrBJCw.png" /><figcaption>RetinaFace failed to detect a face in this image, but YuNet did.</figcaption></figure><h3>Conclusion</h3><p>Based on my tests (which I’d like to emphasize are not the most rigorous in the world; so take them with a grain of salt), I would only consider using either YuNet or RetinaFace, depending on whether speed or accuracy was my primary concern. It’s possible I’d think about using Dlib if I absolutely wanted to minimize false positives, but for my project, it’s down to YuNet or RetinaFace.</p><p>The GitHub repo used for this project is available <a href="https://github.com/astaileyyoung/CineFace">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ab650d8c1225" width="1" height="1" alt=""><hr><p><a href="https://medium.com/pythons-gurus/what-is-the-best-face-detector-ab650d8c1225">What’s the Best Face Detector?</a> was originally published in <a href="https://medium.com/pythons-gurus">Python’s Gurus</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build OpenCV with DNN and CUDA for GPU-Accelerated Face Detection]]></title>
            <link>https://medium.com/@amosstaileyyoung/build-opencv-with-dnn-and-cuda-for-gpu-accelerated-face-detection-27a3cdc7e9ce?source=rss-d901c66b4ae7------2</link>
            <guid isPermaLink="false">https://medium.com/p/27a3cdc7e9ce</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[opencv]]></category>
            <dc:creator><![CDATA[Amos Stailey-Young]]></dc:creator>
            <pubDate>Thu, 29 Feb 2024 17:27:58 GMT</pubDate>
            <atom:updated>2024-02-29T17:27:58.095Z</atom:updated>
            <content:encoded><![CDATA[<p>I’ve been experimenting with various face detection models for my current project and was intrigued by the supposed combination of speed and accuracy in OpenCV’s SSD detector from its Deep Neural Network (DNN) module. But to run this model, I needed OpenCV with CUDA support, which unfortunately meant I had to build OpenCV from source.</p><p>There are many <a href="https://pyimagesearch.com/2018/08/15/how-to-install-opencv-4-on-ubuntu/">tutorials</a> on how to build OpenCV from source, so I’m not trying to reinvent the wheel here. But what works in the tutorials may not work on your machine, which I learned through trial and error. I found the existing tutorials insufficient to deal with the myriad errors I encountered, so I’ve written this account of how I built OpenCV on my machine in case others are dealing with the same baffling errors. I used the following configuration to build OpenCV:</p><p>Nvidia GeForce GTX 1080 TI: Compute Capability 6.1<br>Ubuntu 23.10<br>CUDA 12.0 installed through Ubuntu package manager<br>CUDNN 8.9.2.26 installed through Ubuntu package manager<br>Python 3.11 through Anaconda<br>OpenCV 4.9.0</p><h3>Installing CUDA</h3><p>First, make sure CUDA is installed. I installed it through Ubuntu’s package manager, which is very convenient.</p><pre>sudo apt install nvidia-cuda-toolkit</pre><p>For OpenCV’s DNN module to use a GPU, we also need to install cuDNN.</p><pre>sudo apt install nvidia-cudnn</pre><p>Be aware that many guides assume that CUDA is installed in</p><pre>/usr/local/cuda/</pre><p>But the package manager on Ubuntu 23.10 places it in</p><pre>/usr/lib/nvidia-cuda-toolkit/</pre><p>This will be important later if CMake can’t find the CUDA location.</p><p>Speaking of CMake, it’s required to build OpenCV, so if you don’t already have it installed, run</p><pre>sudo apt install cmake cmake-data build-essential</pre><h3>Building OpenCV</h3><p>We then need to download both OpenCV and OpenCV-contrib source files from GitHub <a href="https://github.com/opencv/opencv">here</a> and <a href="https://github.com/opencv/opencv_contrib">here</a>. OpenCV-contrib files should be placed within the OpenCV directory.</p><p>Now comes the tricky part: building OpenCV. OpenCV is an enormous library with many dependencies. There are a lot of ways the build can go wrong, often without it being noticeable until runtime. There were many times OpenCV was successfully installed with CUDA and able to find the GPU but was unable to run the face detection model because some package needed to be installed or some libraries were missing.</p><pre>cmake \<br>-D WITH_CUDA=ON \<br>-D WITH_CUDNN=ON \<br>-D OPENCV_DNN_CUDA=0N \<br>-D CUDA_ARCH_BIN=6.1 \<br>-D CMAKE_C_COMPILER=gcc-12 \<br>-D CMAKE_CXX_COMPILER=g++-12 \<br>-D OPENCV_EXTRA_MODULES_PATH=/home/amos/sources/opencv/opencv_contrib/modules/ \<br>-D PYTHON3_EXECUTABLE=/home/amos/anaconda3/envs/cv/bin/python \<br>-D PYTHON_LIBRARIES=/home/amos/anaconda3/envs/cv/lib/python3.11/site-packages ..</pre><p>Above is the command I ran to successfully build OpenCV with CUDA support for the DNN module with Python bindings (make sure NumPy is installed in your Python environment). (This configuration only addresses the DNN module, so consult a more general guide for information on how to build the other modules.) I’ll work through how I came to this command.</p><p>The next issue that was a thorn in my side was the CUDA_ARCH_BIN flag. OpenCV easily detected both CUDA and cuDNN on my system. Nevertheless, it would give this error</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QBqWZKNp-UTXymw-YD51Bw.png" /></figure><p>I’m not sure why OpenCV can’t find CUDA_ARCH_BIN, but to get the the compute capability of your GPU run</p><pre>nvidia-smi --query-gpu=compute_cap --format=csv</pre><p>It will return a number that you can use to fill the CUDA_ARCH_BIN flag.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/120/1*P-jQKByyE2RoK0iWrJ610A.png" /></figure><p>After adding the flag, make sure to check that OpenCV correctly found it. If it did, you should see this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/383/1*lUK9xuWWOaWZGtL20vpBeQ.png" /></figure><p>After solving that problem, I immediately encountered another.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/787/1*-1naQcFKfT2wj1E5uL_bgg.png" /></figure><p>This one had me stumped. Earlier I said to put the opencv-contrib source files in the opencv directory so that it could easily find them. Not only did OpenCV not find them on its own, it didn’t find them even when I specified the full path of the directory. Although it <em>seemed</em> like an issue with finding the modules, it was <em>actually</em> an issue with the <em>compiler.</em></p><p>The latest version of the <em>gcc</em> package installed on my system was <em>gcc-13. </em>OpenCV, however, is only compatible with versions up to <em>gcc-12. </em>This problem plagued me initially because OpenCV doesn’t throw an explicit error that identifies the compiler as the problem. I only figured it out when trying to install <a href="https://github.com/davisking/dlib">dlib</a>, which does through an error regarding the compiler. Install with</p><pre>sudo apt install gcc-12 g++-12<br></pre><p>Even after installing, CMake will still find gcc-13, so we need to tell it to use version 12</p><pre>-D CMAKE_C_COMPILER=gcc-12<br>-D CMAKE_CXX_COMPILER=g++-12</pre><p>The next thing to worry about are the Python bindings. In addition to linking to the Python executable, OpenCV requires the NumPy library to be installed. Because I installed OpenCV into an anaconda environment, I needed to point it to that environment’s NumPy package. If we don’t specify a path, however, OpenCV will generally find the system Python.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xkIRfPNJrauEqfFY6DoobQ.png" /></figure><p>In this case, it found my base anaconda python. Since I want to install it into a particular conda environment, I had to include the path to it.</p><pre>-D PYTHON3_EXECUTABLE=/home/amos/anaconda3/envs/cv/bin/python \<br>-D PYTHON_LIBRARIES=/home/amos/anaconda3/envs/cv/lib/python3.11/site-packages</pre><p>Your paths will look different from mine. To know that it worked, look for this in the build notes</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hn5Y25EELVvmmeeBGJ-aaA.png" /></figure><p>Also, make sure that the DNN module will be built</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8qqzw2XxrzbD9v6WE0Z-UQ.png" /><figcaption>Look for dnn in the list of modules.</figcaption></figure><p>I ran into some tricky issues trying to enable the DNN module. CMake would list the DNN module, but even after successfully building, installing, and importing cv2 into Python, I would get an error when running detection. The error turned out to be very misleading, saying that OpenCV needed to be built with WebNN. After some digging, I realized the error didn’t make much sense since WebNN is, as it sounds, for web development, which is not what I was doing. The issue turned out to be with the flag I used to enable the DNN module. I initially used</p><pre>-D WITH_DNN=0N</pre><p>It turned out I needed to use this one</p><pre>-D OPENCV_DNN_CUDA=0N </pre><p>With all the CMake configurations in place, it’s now time to build OpenCV.</p><pre>cmake \<br>-D WITH_CUDA=ON \<br>-D WITH_CUDNN=ON \<br>-D OPENCV_DNN_CUDA=0N \<br>-D CUDA_ARCH_BIN=6.1 \<br>-D CMAKE_C_COMPILER=gcc-12 \<br>-D CMAKE_CXX_COMPILER=g++-12 \<br>-D OPENCV_EXTRA_MODULES_PATH=/home/amos/sources/opencv/opencv_contrib/modules/ \<br>-D PYTHON3_EXECUTABLE=/home/amos/anaconda3/envs/cv/bin/python \<br>-D PYTHON_LIBRARIES=/home/amos/anaconda3/envs/cv/lib/python3.11/site-packages ..<br><br>make -j n #where n is the number of processors to use<br>sudo make install<br></pre><p>After successfully building OpenCV, I still had to get it working with Python. Although I pointed to my anaconda environment in the build configuration, the cv2 Python package is installed to /usr/local/lib/python3.11/site-packages/cv2. To use cv2 in my conda environment, I had to create a symbolic link with the following command</p><pre>ln -s /usr/local/lib/python3.11/site-packages \<br>  /home/amos/anaconda3/cv/lib/python3.11/site-packages</pre><p>Now Python recognized cv2 as installed, but it would still throw an error when I tried to import it.</p><pre>lib/libstdc++.so.6: version `GLIBCXX_3.4.20&#39; not found (required by /usr/lib/x86_64-linux-gnu/libproxy.so.1)<br>Failed to load module: /usr/lib/x86_64-linux-gnu/gio/modules/libgiolibproxy.so</pre><p>To fix this I simply copied the file with</p><pre>cp /usr/lib/gcc/x86_64-linux-gnu/libstdc++.so.6 /home/amos/anaconda3/lib</pre><p>This probably isn’t the best solution — even a symlink would have been better — but I was tired by this point and just wanted it done. (My anaconda install now throws a warning when creating a new environment because of that copy, so find another way if you can).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KS2fKRPFBZehHLcKe1e1Eg.png" /><figcaption>Try not to indiscriminately copy files like I did or you may muck up your environment.</figcaption></figure><h3>Using OpenCV DNN with CUDA in Python</h3><p>Just to show the fruits of my labor, here is a simple script I used to test that OpenCV could use the GPU-accelerated caffe model for face detection.</p><pre>import cv2<br><br># Ensure GPU is available<br>print(cv2.cuda.getCudaEnabledDeviceCount())<br><br># The prototxt and model need to be downloaded separately<br>net = cv2.dnn.readNetFromCaffe(&lt;path-to-prototxt&gt;, &lt;path-to-model&gt;)<br>net.setPreferableBackend(cv2.dnn.DNN_BACKEND_CUDA)<br>net.setPreferableTarget(cv2.dnn.DNN_TARGET_CUDA)<br><br>image = cv2.imread(&lt;path-to-image&gt;)<br>blob = cv2.dnn.blobFromImage(cv2.resize(image, (300, 300)), 1.0,<br>        (300, 300), (104.0, 177.0, 123.0))<br>net.setInput(blob)<br>detections = net.forward()<br><br># The model returns the detections in an odd format a=[:, :, :, :]. <br># Each detection is a[2] while the confidence and bounding box are in <br># a[3]<br>for i in range(faces.shape[2]):<br>    confidence = faces[0, 0, i, 2]<br>    if confidence &gt; threshold:<br>        (h, w) = image.shape[:2]<br>        box = faces[0, 0, i, 3:7] * np.array([w, h, w, h])<br>        (startX, startY, endX, endY) = box.astype(&quot;int&quot;)<br>        cv2.rectangle(image, (startX, startY), (endX, endY),<br>            (0, 0, 255), 2)<br>cv2.imshow(image)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*Nl4q86Rt4sV4LLESKkkxsQ.jpeg" /></figure><p>Ta-da! GPU-accelerated face detection with OpenCV’s DNN module finally working.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=27a3cdc7e9ce" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Identifying Shot Scale with Artificial Intelligence]]></title>
            <link>https://medium.com/@amosstaileyyoung/identifying-shot-scale-with-artificial-intelligence-a273a225e44b?source=rss-d901c66b4ae7------2</link>
            <guid isPermaLink="false">https://medium.com/p/a273a225e44b</guid>
            <category><![CDATA[hollywood]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[cinema]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[history]]></category>
            <dc:creator><![CDATA[Amos Stailey-Young]]></dc:creator>
            <pubDate>Sun, 22 Oct 2023 18:08:26 GMT</pubDate>
            <atom:updated>2023-10-22T18:27:01.744Z</atom:updated>
            <content:encoded><![CDATA[<h4>Shot Scale in Classical Hollywood: A Historical Analysis</h4><p><em>After a long hiatus due to starting a new job, this post is the fourth in a </em><a href="https://medium.com/@amosstaileyyoung/list/identifying-shot-scale-with-artificial-intelligence-cc22425281a7"><em>series</em></a><em>. Subsequent posts will be released every other Sunday. The code for this project can be found on my </em><a href="https://github.com/astaileyyoung/ShotScaleSample"><em>GitHub</em></a><em>. The Google Colab notebook used to analyze the data can be found </em><a href="https://colab.research.google.com/drive/1ATFpGvPMeOeAnqS6oSOThtgL9IPDRbJT?usp=sharing"><em>here</em></a><em>.</em></p><p>The “scale” of an image is integral to how we think about movies. Words like “close-up” or “establishing shot” are used so habitually that it’s hard to imagine life without them. But how has shot scale changed over time? Wouldn’t it be nice to have some idea of its history?</p><p>Because the scale of a frame is highly correlated to the size of the most prominent face contained within it, I ran a facial detection algorithm over a representative sample of more than 4,000 Hollywood movies produced between 1915 and 1970. Taking an average for each film, and then averaging those by year, can show us how shot scale changes historically.</p><p>Film scholars have generally argued that the arrival of sound (circa 1927–1928) severely limited the cinematic possibilities developed during the silent era (notably lampooned by <em>Singin’ in the Rain </em>[1952]).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*XKse2GYy83Rw7fmlhuwnYQ.jpeg" /><figcaption>Because of the noise of the camera, early sound films put cameras in soundproof booths.</figcaption></figure><p>In particular, the realities of early sound recording meant the camera had to be largely stationary, constraining the meticulous camera movements of the late silent era. While not always mentioned explicitly, the enormous close-ups were also lost. If the arrival of sound really did affect film style, specifically the frequency of close-ups, we should be able to see it in the data, which I’ve plotted below.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fplotly.com%2F%7EHyperSloth%2F468.embed%3Fautosize%3Dtrue&amp;display_name=Plotly&amp;url=https%3A%2F%2Fchart-studio.plotly.com%2F%7EHyperSloth%2F468%2F&amp;image=https%3A%2F%2Fchart-studio.plotly.com%2Fstatic%2Fwebapp%2Fimages%2Fplotly-logo.8d56a320dbb8.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=plotly" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/4b5e154b0120c15a878d427a4e2abab5/href">https://medium.com/media/4b5e154b0120c15a878d427a4e2abab5/href</a></iframe><p>Just looking at the plot tells a story. We see a remarkable rise in shot scale followed by a sharp decline. The shift is so abrupt, dropping by about half in a period of only three years, that it cries out for an explanation. Since this decline occurred after the introduction of sound, the data sure make a compelling case that the arrival of sound had a strong effect on shot scale.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K3ZyAShh5ubGgvKiJtpRpg.jpeg" /><figcaption>An example of the large close-ups common during the late silent era. From <strong>Joan of Arc</strong> (1928).</figcaption></figure><p>Perhaps more interesting than the sudden drop in relative face size is that it remained around this level for most of what we call “classical” Hollywood. It perhaps counters claims made by many scholars that the effects of the transition to sound temporary and basically resolved by the mid-1930s. The data suggests that, at least regarding shot scale, the changes brought on by the arrival of sound were much more lasting than we may have thought. It was not until 1970, over 40 years after the first sound film, that shot scale again reached the level of the late silent era.</p><p>This rather straightforward analysis demonstrates the possibilities that AI has for media analytics. In this case, the data helps confirm the transition to sound as the single most impactful event on shot scale during “classical” Hollywood. It empirically supports the consensus view that the transition to sound led to drastic changes in film style.</p><h4>Shot Scale and the Demise of Old Hollywood</h4><p>The effect of sound is remarkably intense, but it’s not the only significant development. In some ways, the rapid increase in face size after 1960 is the more interesting phenomenon. Because the 1960s were a time of great upheaval for Hollywood — the “studio system” had already begun disintegrating in the 1950s — the increase in shot scale can get lost in the chaos. However, the intensity of the transformation is striking. Face size nearly doubled during the 1960s, a sea change analogous to the arrival of sound. Rarely has the scale of this change been acknowledged, however, possibly because the change occurred gradually enough to go relatively unnoticed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/755/1*pp-o2zGsd5HpbteRcfXNEw.jpeg" /><figcaption>Extreme close-ups like the above from <strong>The Good, the Bad and the Ugly </strong>(1966) became much more common during 1960s Hollywood. The model actually fails to detect a face in the image because it is so close.</figcaption></figure><p>What could possibly explain such a rapid increase in shot scale? Answering that question is well beyond the scope of this post. Some scholars have already proposed explanations that may be relevant here, but few address the problem directly.</p><h4>Widescreen</h4><p>According to some, the introduction of widescreen led to more close-ups. More room on the sides of the image meant more space to fill. Also, the lateral space meant tight close-ups were “balanced” by the negative space of the more spacious screen. In this argument, the new widescreen technology disrupted aesthetic norms, thus prompting a shift in film style.</p><p>As we can see in the data, if the above argument is correct, the aesthetic transformation lagged behind the transition to widescreen, which began in 1953 and proceeded rapidly. Most films were using the new widescreen technology just a few years later. It was not until 1960, however, that face size started to increase. Because of the delay, it’s difficult to interpret any causal relationship between widescreen and increasing shot scale.</p><p>However, there may be an intriguing way to test this theory. We could compare widescreen to “flat” films during the same time period. If widescreen genuinely drove the increase in shot scale, we would expect significant differences between the shot scale of wide vs. standard films. If no such difference exists, that would seriously undermine the widescreen theory. I may explore this in a later post.</p><h4>Television</h4><p>Another common explanation for the increasing frequency of close-ups toward the end of the studio system identifies television as the culprit. The reduced frame of the TV, the thinking goes, required more close-ups, which then influenced film style. The chart above also undermines this explanation since television was already a powerful force by the mid-1950s. If it did have an effect, there is again a “lag time” within the relationship. It may be possible to test this empirically. We would need a representative sample of television over the same time period to compare against, however, but that is a project of its own.</p><p>Knowing how shot scale changed <em>after </em>1970 would be incredibly helpful. It might give us insight into why earlier changes occurred. But again, this is its own project. For reasons I’ve discussed earlier, it is much harder to collect films after 1970 because of copyrights. Older films are more easily attainable because they are more frequently in the public domain, or no one cares about the copyright.</p><h4>Next Steps</h4><p>As we’ve seen, the chart above tells us <em>how </em>shot scale changed but not <em>why</em>. What factors drove those changes? I’ve reviewed a few possible explanations in this post, but I’ll need to dive deeper into the data to evaluate them. Subsequent posts will examine shot scale in relation to factors like genre, widescreen, color, production company, and director. Closely parsing the data will hopefully reveal which factors are most responsible for historical changes in shot scale. But it can also tell us other things, such as which directors frequently used close-ups and which did not.</p><h4>Previous Posts</h4><ul><li><a href="https://medium.com/@amosstaileyyoung/identifying-shot-scale-with-artificial-intelligence-d7be55f8903">Identifying Shot Scale with Artificial Intelligence</a></li><li><a href="https://medium.com/@amosstaileyyoung/identifying-shot-scale-with-artificial-intelligence-54011062e0bf">Identifying Shot Scale with Artificial Intelligence</a></li><li><a href="https://medium.com/@amosstaileyyoung/identifying-shot-scale-with-artificial-intelligence-41536bdeae6d">Identifying Shot Scale with Artificial Intelligence</a></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*7lyCoc5aeXPFACna573fBw.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a273a225e44b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Identifying Shot Scale with Artificial Intelligence]]></title>
            <link>https://medium.com/@amosstaileyyoung/identifying-shot-scale-with-artificial-intelligence-41536bdeae6d?source=rss-d901c66b4ae7------2</link>
            <guid isPermaLink="false">https://medium.com/p/41536bdeae6d</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[cinema]]></category>
            <category><![CDATA[hollywood]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Amos Stailey-Young]]></dc:creator>
            <pubDate>Thu, 13 Oct 2022 18:49:09 GMT</pubDate>
            <atom:updated>2023-10-22T18:26:00.950Z</atom:updated>
            <content:encoded><![CDATA[<h4>CineScale</h4><p><em>This post is the third in a </em><a href="https://medium.com/@amosstaileyyoung/list/identifying-shot-scale-with-artificial-intelligence-cc22425281a7"><em>series</em></a><em>. The code for this project can be found on my </em><a href="https://github.com/astaileyyoung/ShotScaleSample"><em>GitHub</em></a><em>. The Google Colab notebook used to analyze the data can be found </em><a href="https://colab.research.google.com/drive/1ATFpGvPMeOeAnqS6oSOThtgL9IPDRbJT?usp=sharing"><em>here</em></a><em>.</em></p><p>As I discussed in my <a href="https://medium.com/@amosstaileyyoung/identifying-shot-scale-with-artificial-intelligence-54011062e0bf">previous post</a>, the folks at CineScale have released a new and unique dataset called <a href="https://cinescale.github.io/">CineScale</a> that attempts to catalog shot scale. They have trained a Convolutional Neural Network to classify images as either close, medium, or long shots. And because they’ve released this model to the public, I can use it on my own sample of Hollywood films. This post examines the results of applying the CineScale model to a representative sample of approximately 3500 films produced in the US between 1915 and 1970.</p><p>CineScale uses machine learning (i.e., artificial intelligence) to label images as a close, medium, or long shot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LbtEF4-dFXd_D2F3HjIFqg.jpeg" /><figcaption>Example of the data collection process.</figcaption></figure><p>CineScale used a “<a href="https://en.wikipedia.org/wiki/Supervised_learning">supervised learning</a>” approach where two human “annotators” manually labeled approximately 792 thousand frames according to the schema above. CineScale then trained a <a href="https://en.wikipedia.org/wiki/Convolutional_neural_network">Convolutional Neural Network</a> that can automatically classify any image on this dataset.</p><p>The model is available for download on the <a href="https://cinescale.github.io/examples/model_shotscale_967.h5">CineScale website</a>. I’ve written about my film sample in <a href="https://medium.com/@amosstaileyyoung/using-mits-places365-to-track-location-shooting-in-american-cinema-the-sample-414366c4aa91">another context</a> for the curious.</p><p>Unfortunately, there isn’t much to discuss here. CineScale is a novel and innovative application of artificial intelligence and machine learning to the study of cinema. Film studies, and the digital humanities more broadly, can benefit significantly from projects in the data analysis space like CineScale. However, the “resolution” of the model is too low to capture any information about how shot scale has changed historically. Further, the results of my analysis cast some grave doubts on the integrity of the CineScale model.</p><p>Whether we examine our sample by year of production, genre, or studio, we get essentially the same proportions between close, medium, and long shots. The variation is negligible and is explicable by randomness. Because the plots (shown below) are so similar, I’ll discuss them as a group.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fplotly.com%2F%7EHyperSloth%2F664.embed%3Fautosize%3Dtrue&amp;display_name=Plotly&amp;url=https%3A%2F%2Fchart-studio.plotly.com%2F%7EHyperSloth%2F664%2F&amp;image=https%3A%2F%2Fchart-studio.plotly.com%2Fstatic%2Fwebapp%2Fimages%2Fplotly-logo.8d56a320dbb8.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=plotly" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/8f6c562efa917776d94af99a06b037bf/href">https://medium.com/media/8f6c562efa917776d94af99a06b037bf/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fplotly.com%2F%7EHyperSloth%2F669.embed%3Fautosize%3Dtrue&amp;display_name=Plotly&amp;url=https%3A%2F%2Fchart-studio.plotly.com%2F%7EHyperSloth%2F669%2F&amp;image=https%3A%2F%2Fchart-studio.plotly.com%2Fstatic%2Fwebapp%2Fimages%2Fplotly-logo.8d56a320dbb8.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=plotly" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/2d9ac1523d226839b6afa89a94a32008/href">https://medium.com/media/2d9ac1523d226839b6afa89a94a32008/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fplotly.com%2F%7EHyperSloth%2F671.embed%3Fautosize%3Dtrue&amp;display_name=Plotly&amp;url=https%3A%2F%2Fchart-studio.plotly.com%2F%7EHyperSloth%2F671%2F&amp;image=https%3A%2F%2Fchart-studio.plotly.com%2Fstatic%2Fwebapp%2Fimages%2Fplotly-logo.8d56a320dbb8.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=plotly" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/91e3f81e3f2f01d2802debffe6ba6753/href">https://medium.com/media/91e3f81e3f2f01d2802debffe6ba6753/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fplotly.com%2F%7EHyperSloth%2F673.embed%3Fautosize%3Dtrue&amp;display_name=Plotly&amp;url=https%3A%2F%2Fchart-studio.plotly.com%2F%7EHyperSloth%2F673%2F&amp;image=https%3A%2F%2Fchart-studio.plotly.com%2Fstatic%2Fwebapp%2Fimages%2Fplotly-logo.8d56a320dbb8.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=plotly" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/e683d9e19a144786beaba62ae487fcf0/href">https://medium.com/media/e683d9e19a144786beaba62ae487fcf0/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fplotly.com%2F%7EHyperSloth%2F675.embed%3Fautosize%3Dtrue&amp;display_name=Plotly&amp;url=https%3A%2F%2Fchart-studio.plotly.com%2F%7EHyperSloth%2F675%2F&amp;image=https%3A%2F%2Fchart-studio.plotly.com%2Fstatic%2Fwebapp%2Fimages%2Fplotly-logo.8d56a320dbb8.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=plotly" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/11268ee94bf7df2580a718738c62eae9/href">https://medium.com/media/11268ee94bf7df2580a718738c62eae9/href</a></iframe><p>Because the data does not seem to vary according to any feature of the dataset, the only conclusion we can draw is that the ratio of the shots in American cinema between 1915 and 1970 remained relatively unchanged. Such a conclusion is actually surprising because it seemingly contradicts the subjective experience of many researchers. Somewhat speculatively, I would say that most scholars would assume that the close-up rate would differ according to historical period, whether due to the introduction of sound or the emergence of widescreen. The model does not predict this, however. So we have a discrepancy between what scholars anticipate from the data and the data itself. How do we account for this discrepancy?</p><p>There are two kinds of reasons why the data may not vary according to feature. Either the model is accurate and the data does vary little in actual reality, or the model is inaccurate and misses changes that actually happen. Let’s be charitable and assume for the moment that the model is correct. What would explain the lack of change in the ratio of shot scales?</p><p>If the model truly captures some aspect of reality, then we may have something akin to a “<a href="https://en.wikipedia.org/wiki/Golden_ratio">golden ratio</a>” of shot proportions. It’s somewhat unclear why such a ratio might exist, however. Is it some consequence of human perception? If that’s the case, maybe we’ve stumbled upon an artistic or cultural “law.”</p><p>The other way to explain the low variance is that the model does not adequately capture the phenomena it purports to represent; in this case, shot scale. For adherents to Occam’s razor, that explanation is much more likely than the first one. There is also some compelling evidence to support it.</p><p>Machine learning models, and Artificial Neural Networks like CineScale especially, are often accused of operating like “black boxes” since even their creators have difficulty explaining how they work. A lot can go wrong with these models in ways that are hard to predict.</p><p>The most concerning result from the CineScale model is the exceptional rarity of “long shots” in the sample. The highest percentage of long shots in a film is around 0.4%, which means they essentially don’t exist as a shot class in American cinema, according to the CineScale data. By not regularly predicting long shots, this model has almost turned a multi-class problem into a binary one.</p><p>Further, the average values hover around 2/3 and 1/3 for medium and close shots respectively, which is suspicious. Since there are three classes in total, those fractions are special, which makes it questionable that the averages just happen to be coincidentally close to them.</p><p>Hopefully, I’m wrong about CineScale. At the moment, though, I have some serious doubts regarding the validity of their model. It’s disappointing, especially since I had such high hopes initially. But the lack of variance in the data makes it impossible to conclude much of anything. And when combined with the model dropping the “long shot” class and the proportions hovering around 1/3, it suggests the model has somehow “overfitted” the data. Perhaps I’m wrong, which I hope I am. Determining whether the model is overfit is not easy. But we can explore the issue in greater depth when examining the results of applying <a href="https://medium.com/@amosstaileyyoung/identifying-shot-scale-with-artificial-intelligence-d7be55f8903">my method</a> to my sample. That is coming up in the next post.</p><h4>Previous Posts</h4><ul><li><a href="https://medium.com/@amosstaileyyoung/identifying-shot-scale-with-artificial-intelligence-d7be55f8903">Identifying Shot Scale with Artificial Intelligence</a></li><li><a href="https://medium.com/@amosstaileyyoung/identifying-shot-scale-with-artificial-intelligence-54011062e0bf">Identifying Shot Scale with Artificial Intelligence</a></li></ul><h4>Next Posts</h4><p><a href="https://medium.com/@amosstaileyyoung/identifying-shot-scale-with-artificial-intelligence-a273a225e44b">Identifying Shot Scale with Artificial Intelligence</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=41536bdeae6d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>