title: How to optimize a palette-based image recoloring algorithm
body: <p>I've a scenario, where I generate a color palette against a specific image. Then I want to click on any of the palette colors n and select a new color to be put on all the pixels with the previous color code. I'm done, and it's working, but I need your <strong>help on optimizing its results and time</strong>. The code to generate the palette using <strong>color thief</strong> is:</p>
  
  <pre><code>function make_pallete(){
      var images = document.getElementById('default_img');
      colors = colorThief.getPalette(images, 8);
      for (var i = 0 ; i &lt; colors.length; i++) {
          $('#swatches').append("&lt;div class='swatch' style='background-color:rgb("+       colors[i][0]+ ","+ colors[i][1] + "," + colors[i][2] +")'&gt;&lt;/div&gt;");
      }
  }
  </code></pre>
  
  <p>And the Django view, where I'm performing recoloring is:</p>
  
  <pre><code>def recolor_image(request):
      if request.method == "POST":
          pic = request.POST.get("image")
          old_rgb = request.POST.getlist("old_rgb[]")
          new_rgb = request.POST.getlist("new_rgb[]")
          path = "D:/pysofts/flagcarpets" + pic
          pic  = path
          picture = Image.open(pic)
          # Get the size of the image
          width,height = picture.size
          print old_rgb
          for x in range(0, width):
              for y in  range(0, height):
                  current_color = picture.getpixel((x,y))
                  r,g,b = current_color
                  if r in range(int(old_rgb[0]) - 50, int(old_rgb[0]) + 50) and g in     range(int(old_rgb[1]) - 50, int(old_rgb[1]) + 50) and b in range(int(old_rgb[2]) - 50, int(old_rgb[2]) + 50):
                      r = int(new_rgb[0])
                      g = int(new_rgb[1])
                      b = int(new_rgb[2])
                 new_color = (r,g,b)
                 picture.putpixel((x,y), new_color)
          picture.save(path)
          return HttpResponse(pic)
  </code></pre>
  
  <p>As I said, it's recoloring the image, but the efficiency is poor (it doesn't put new color to every previous pixel) n it takes about 30 seconds to recolor the image. What would a more precise algorithm be?</p>