මොනා ලිසාගේ පලතේ ඇමරිකානු ගොතික්: පික්සල් නැවත සකස් කරන්න


379

ඔබට සත්‍ය වර්ණ රූප දෙකක් ලබා දී ඇත, ප්‍රභවය සහ පලට්. ඔවුන්ට අවශ්‍යයෙන්ම එකම මානයන් නොමැති නමුත් ඒවායේ ප්‍රදේශ එක හා සමාන බව සහතික වේ, එනම් ඔවුන්ට එකම පික්සෙල් සංඛ්‍යාවක් ඇත.

ඔබේ කර්තව්යය වන්නේ ප්රභවයේ වඩාත් නිවැරදිව පෙනෙන පිටපතක් නිපදවන ඇල්ගොරිතමයක් නිර්මාණය කිරීමයි. මෙම පිටපතෙහි එක් එක් පික්සෙල් එක වරක් අද්විතීය ස්ථානයක භාවිතා කළ යුතුය. පිටපතට ප්‍රභවයට සමාන මානයන් තිබිය යුතුය.

මෙම සීමාවන් සපුරාලීම සහතික කිරීම සඳහා මෙම පයිතන් පිටපත භාවිතා කළ හැකිය:

from PIL import Image
def check(palette, copy):
    palette = sorted(Image.open(palette).convert('RGB').getdata())
    copy = sorted(Image.open(copy).convert('RGB').getdata())
    print 'Success' if copy == palette else 'Failed'

check('palette.png', 'copy.png')

පරීක්ෂා කිරීම සඳහා පින්තූර කිහිපයක් මෙන්න. ඔවුන් සියල්ලන්ටම එකම ප්රදේශයක් ඇත. ඔබේ ඇල්ගොරිතම ඇමරිකානු ගොතික් සහ මොනා ලිසා පමණක් නොව සමාන ප්‍රදේශ සහිත ඕනෑම රූප දෙකක් සඳහා ක්‍රියා කළ යුතුය. ඔබ ඇත්ත වශයෙන්ම ඔබේ ප්‍රතිදානය පෙන්විය යුතුය.

ඇමරිකානු ගොතික් මොනාලිසා තරු රාත්‍රිය කෑගැසීම ගඟ දේදුන්න

ප්‍රසිද්ධ සිතුවම්වල රූප සඳහා විකිපීඩියාවට ස්තූතියි.

ලකුණු කිරීම

මෙය ජනප්‍රිය තරගයක් බැවින් වැඩිම ඡන්ද ප්‍රතිශතයක් දිනා ගනී. නමුත් මට විශ්වාසයි මේ සමඟ නිර්මාණශීලී වීමට බොහෝ ක්‍රම තිබේ!

සජීවිකරණය

මිලිනොන්ගේ අදහස වූයේ පික්සෙල් නැවත සකස් කිරීම දැකීම සිසිල් වනු ඇති බවයි. මමත් හිතුවා ඉතින් මම මේ පයිතන් පිටපත ලිව්වේ එකම වර්ණවලින් සාදන ලද පින්තූර දෙකක් ගෙන ඒවා අතර අතරමැදි රූප අඳින්න. යාවත්කාලීන කිරීම: මම එය සංශෝධනය කළෙමි, එවිට සෑම පික්සෙල් එකක්ම එහි අවම මුදල ගෙන යයි. එය තවදුරටත් අහඹු නොවේ.

පළමුවැන්න මොනා ලීසා ඇඩිට්සුගේ ඇමරිකානු ගොතික් බවට පත්වීමයි. ඊළඟට බිට්පෝනර්ගේ ඇමරිකානු ගොතික් (මොනා ලිසා වෙතින්) ඇඩිට්සු බවට පත්වේ. අනුවාද දෙක එකම වර්ණ තලය බෙදා ගැනීම පුදුම සහගතය.

මොනා ලිසා සිට ඇමරිකානු ගොතික් සජීවිකරණය දක්වා මොනා ලිසා වලින් සාදන ලද ඇමරිකානු ගොතික් අනුවාද දෙකක් අතර සජීවිකරණය

ප්‍රති results ල ඇත්තෙන්ම විශ්මය ජනකයි. මෙන්න ඇඩිට්සුගේ දේදුන්න මොනා ලිසා (විස්තර පෙන්වීමට ප්‍රමාදයි).

දේදුන්න ගෝලාකාර මොනා ලිසා සජීවිකරණයට

මෙම අන්තිම සජීවිකරණය අනිවාර්යයෙන්ම තරඟයට සම්බන්ධ නොවේ. රූපයක් අංශක 90 ක් භ්‍රමණය කිරීමට මගේ ස්ක්‍රිප්ට් භාවිතා කළ විට කුමක් සිදුවේදැයි එය පෙන්වයි.

ගස් භ්‍රමණ සජීවිකරණය


22
ඔබේ ප්‍රශ්නයේ වැඩි වීමක් ලබා ගැනීම සඳහා, “ඇමරිකානු ගොතික් මොනා ලිසාගේ
ප්‍රස්තාරයේ

14
හායි, මට මේ මුල් අභියෝගයට සුබ පතන්න අවශ්‍යයි! ඉතා නැවුම් සහ රසවත්.
bolov

6
මෙය [කේත-ගොල්ෆ්] නොවීම ගැන මට සතුටුයි.
මින්ග්-ටැං

14
මම මෙම පිටුවට පිවිසෙන සෑම අවස්ථාවකම මගේ ජංගම දත්ත සීමාවට දරුණු පිළිස්සුම් ඇති වේ.
දෛශිකකරණය

5
ආශ්‍රිත: github.com/jcjohnson/neural-style
Vi.

Answers:


160

ජාවා - ප්‍රගතිශීලී සසම්භාවී පරිවර්තනයක් සහිත GUI

මම බොහෝ දේ අත්හදා බැලුවෙමි, සමහර ඒවා ඉතා සංකීර්ණ විය, පසුව මම අවසානයේදී මෙම සාපේක්ෂ සරල කේතයට නැවත පැමිණියෙමි:

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.Timer;

@SuppressWarnings("serial")
public class CopyColors extends JFrame {
    private static final String SOURCE = "spheres";
    private static final String PALETTE = "mona";
    private static final int COUNT = 10000;
    private static final int DELAY = 20;
    private static final int LUM_WEIGHT = 10;

    private static final double[] F = {0.114, 0.587, 0.299};
    private final BufferedImage source;
    protected final BufferedImage dest;
    private final int sw;
    private final int sh;
    private final int n;
    private final Random r = new Random();
    private final JLabel l;

    public CopyColors(final String sourceName, final String paletteName) throws IOException {
        super("CopyColors by aditsu");
        source = ImageIO.read(new File(sourceName + ".png"));
        final BufferedImage palette = ImageIO.read(new File(paletteName + ".png"));
        sw = source.getWidth();
        sh = source.getHeight();
        final int pw = palette.getWidth();
        final int ph = palette.getHeight();
        n = sw * sh;
        if (n != pw * ph) {
            throw new RuntimeException();
        }
        dest = new BufferedImage(sw, sh, BufferedImage.TYPE_INT_RGB);
        for (int i = 0; i < sh; ++i) {
            for (int j = 0; j < sw; ++j) {
                final int x = i * sw + j;
                dest.setRGB(j, i, palette.getRGB(x % pw, x / pw));
            }
        }
        l = new JLabel(new ImageIcon(dest));
        add(l);
        final JButton b = new JButton("Save");
        add(b, BorderLayout.SOUTH);
        b.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(final ActionEvent e) {
                try {
                    ImageIO.write(dest, "png", new File(sourceName + "-" + paletteName + ".png"));
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        });
    }

    protected double dist(final int x, final int y) {
        double t = 0;
        double lx = 0;
        double ly = 0;
        for (int i = 0; i < 3; ++i) {
            final double xi = ((x >> (i * 8)) & 255) * F[i];
            final double yi = ((y >> (i * 8)) & 255) * F[i];
            final double d = xi - yi;
            t += d * d;
            lx += xi;
            ly += yi;
        }
        double l = lx - ly;
        return t + l * l * LUM_WEIGHT;
    }

    public void improve() {
        final int x = r.nextInt(n);
        final int y = r.nextInt(n);
        final int sx = source.getRGB(x % sw, x / sw);
        final int sy = source.getRGB(y % sw, y / sw);
        final int dx = dest.getRGB(x % sw, x / sw);
        final int dy = dest.getRGB(y % sw, y / sw);
        if (dist(sx, dx) + dist(sy, dy) > dist(sx, dy) + dist(sy, dx)) {
            dest.setRGB(x % sw, x / sw, dy);
            dest.setRGB(y % sw, y / sw, dx);
        }
    }

    public void update() {
        l.repaint();
    }

    public static void main(final String... args) throws IOException {
        final CopyColors x = new CopyColors(SOURCE, PALETTE);
        x.setSize(800, 600);
        x.setLocationRelativeTo(null);
        x.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        x.setVisible(true);
        new Timer(DELAY, new ActionListener() {
            @Override
            public void actionPerformed(final ActionEvent e) {
                for (int i = 0; i < COUNT; ++i) {
                    x.improve();
                }
                x.update();
            }
        }).start();
    }
}

අදාළ සියලු පරාමිතීන් පන්තියේ ආරම්භයේ නියතයන් ලෙස අර්ථ දක්වා ඇත.

වැඩසටහන මුලින් පලත් රූපය ප්‍රභව මානයන් වෙත පිටපත් කරයි, පසුව නැවත නැවතත් අහඹු පික්සල් 2 ක් තෝරාගෙන ඒවා ප්‍රභව රූපයට සමීප වේ නම් ඒවා මාරු කරයි. "සමීප" යන්න අර්ථ දැක්වෙන්නේ වර්ණ දුර ශ්‍රිතයක් භාවිතා කර r, g, b සංරචක (ලූමා-බර) සහ සමස්ත ලූමා වෙනස සමඟ ලූමා සඳහා වැඩි බරක් ගණනය කරයි.

හැඩයන් සෑදීමට තත්පර කිහිපයක් ගත වේ, නමුත් වර්ණ එකට පැමිණීමට තව කාලයක් ගතවේ. ඔබට ඕනෑම වේලාවක වත්මන් රූපය සුරැකිය හැක. මම සාමාන්‍යයෙන් ඉතිරි කිරීමට පෙර මිනිත්තු 1-3 ක් පමණ බලා සිටියෙමි.

ප්රතිපල:

වෙනත් පිළිතුරු මෙන් නොව, මෙම පින්තූර සියල්ලම එකම පරාමිතීන් (ගොනු නාම හැර) භාවිතා කර ජනනය කරන ලද්දකි.

ඇමරිකානු ගොතික් පලත්

මොනා-ගොතික් කෑගැසීම-ගොතික්

මොනා ලීසා පලත්

ගොතික්-මොනා කෑගැසීම-මොනා ගෝලාකාර-මොනා

තරු රාත්‍රී පලත්

මොනා-රාත්‍රිය කෑගැසීම-රාත්‍රිය ගෝලාකාර-රාත්‍රිය

Scream palette

ගොතික්-කෑගැසීම මොනා-කෑගැසීම රාත්‍රී කෑගැසීම ගෝලාකාර-කෑගැසීම

ගෝලාකාර පලත්

මම හිතන්නේ මෙය වඩාත්ම දුෂ්කර පරීක්ෂණය වන අතර සෑම කෙනෙකුම ඔවුන්ගේ ප්‍රති results ල මෙම පලත් සමඟ පළ කළ යුතුය:

ගොතික්-ගෝල මොනා-ගෝල කෑගැසීම්-ගෝලාකාර

කණගාටුයි, මට ගංගා රූපය එතරම් සිත්ගන්නාසුළු නොවූ නිසා මම එය ඇතුළත් කර නැත.

මම https://www.youtube.com/watch?v=_-w3cKL5teM හි වීඩියෝවක් ද එක් කළෙමි , එය වැඩසටහන කරන්නේ කුමක්ද යන්න පෙන්වයි (හරියටම තත්‍ය කාලීනව නොව ඒ හා සමානයි) එවිට එය ක්‍රමානුකූලව පික්සල් චලනය කැල්වින්ගේ පයිතන් භාවිතයෙන් පෙන්වයි ස්ක්‍රිප්ට්. අවාසනාවට, යූ ටියුබ් කේතන / සම්පීඩනය මගින් වීඩියෝවල ගුණාත්මකභාවය සැලකිය යුතු ලෙස හානි වී ඇත.


2
@ ක්වින්කන්ක්ස් මම ඉන්වොක්ලෙටර්ට කතා නොකරමි, මට වෙඩි තියන්න: p එසේම, ස්තූතියි :)
ඇඩිට්සු ඉවත්ව ගියේ එස්ඊ ඊවිල්

16
මේ දක්වා ඇති හොඳම පිළිතුර ...
යුවල් ෆිල්මස්

8
සැකයක් ඇති විට, තිරිසන් එය බල කරයිද? විශිෂ්ට විසඳුමක් සේ පෙනේ, මේ සඳහා සජීවීකරණයක් දැකීමට මා කැමතිය, සමහර විට gif වෙනුවට වීඩියෝවක් පවා.
ලිලියන්තල්

3
කුඩා වැඩිදියුණු කිරීමක් සඳහා ඔබට ඇල්ගොරිතම පූර්ණ අනුකම්පිත ඇනලයිලිං වෙත ටිකක් දිගු කළ හැකිය . ඔබ කරන දේ දැනටමත් ඉතා ආසන්නයි (නමුත් එය කෑදරකම). දුර අවම කරන ප්‍රේරණය සොයා ගැනීම දුෂ්කර ප්‍රශස්තිකරණ ගැටළුවක් සේ පෙනේ, එබැවින් මේ ආකාරයේ සුවදායීතාව සුදුසුය. Il ලිලියන්තල් මෙය තිරිසන් බල කිරීමක් නොවේ, එය ඇත්ත වශයෙන්ම බහුලව භාවිතා වන ප්‍රශස්තිකරණ ක්‍රමවේදයන්ට සමීප වේ.
සාබොල්ක්ස්

3
මෙම ඇල්ගොරිතම මෙතෙක් හොඳම ප්‍රති results ල ලබා ඇත. එය ඉතා සරල ය. මෙය මට පැහැදිලි ජයග්‍රාහකයෙකු බවට පත් කරයි.
ලීෆ්

119

ජාවා

import java.awt.Point;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;
import javax.imageio.ImageIO;

/**
 *
 * @author Quincunx
 */
public class PixelRearranger {

    public static void main(String[] args) throws IOException {
        BufferedImage source = ImageIO.read(resource("American Gothic.png"));
        BufferedImage palette = ImageIO.read(resource("Mona Lisa.png"));
        BufferedImage result = rearrange(source, palette);
        ImageIO.write(result, "png", resource("result.png"));
        validate(palette, result);
    }

    public static class MInteger {
        int val;

        public MInteger(int i) {
            val = i;
        }
    }

    public static BufferedImage rearrange(BufferedImage source, BufferedImage palette) {
        BufferedImage result = new BufferedImage(source.getWidth(),
                source.getHeight(), BufferedImage.TYPE_INT_RGB);

        //This creates a list of points in the Source image.
        //Then, we shuffle it and will draw points in that order.
        List<Point> samples = getPoints(source.getWidth(), source.getHeight());
        System.out.println("gotPoints");

        //Create a list of colors in the palette.
        rgbList = getColors(palette);
        Collections.sort(rgbList, rgb);
        rbgList = new ArrayList<>(rgbList);
        Collections.sort(rbgList, rbg);
        grbList = new ArrayList<>(rgbList);
        Collections.sort(grbList, grb);
        gbrList = new ArrayList<>(rgbList);
        Collections.sort(gbrList, gbr);
        brgList = new ArrayList<>(rgbList);
        Collections.sort(brgList, brg);
        bgrList = new ArrayList<>(rgbList);
        Collections.sort(bgrList, bgr);

        while (!samples.isEmpty()) {
            Point currentPoint = samples.remove(0);
            int sourceAtPoint = source.getRGB(currentPoint.x, currentPoint.y);
            int bestColor = search(new MInteger(sourceAtPoint));
            result.setRGB(currentPoint.x, currentPoint.y, bestColor);
        }
        return result;
    }

    public static List<Point> getPoints(int width, int height) {
        HashSet<Point> points = new HashSet<>(width * height);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                points.add(new Point(x, y));
            }
        }
        List<Point> newList = new ArrayList<>();
        List<Point> corner1 = new LinkedList<>();
        List<Point> corner2 = new LinkedList<>();
        List<Point> corner3 = new LinkedList<>();
        List<Point> corner4 = new LinkedList<>();

        Point p1 = new Point(width / 3, height / 3);
        Point p2 = new Point(width * 2 / 3, height / 3);
        Point p3 = new Point(width / 3, height * 2 / 3);
        Point p4 = new Point(width * 2 / 3, height * 2 / 3);

        newList.add(p1);
        newList.add(p2);
        newList.add(p3);
        newList.add(p4);
        corner1.add(p1);
        corner2.add(p2);
        corner3.add(p3);
        corner4.add(p4);
        points.remove(p1);
        points.remove(p2);
        points.remove(p3);
        points.remove(p4);

        long seed = System.currentTimeMillis();
        Random c1Random = new Random(seed += 179426549); //The prime number pushes the first numbers apart
        Random c2Random = new Random(seed += 179426549); //Or at least I think it does.
        Random c3Random = new Random(seed += 179426549);
        Random c4Random = new Random(seed += 179426549);

        Dir NW = Dir.NW;
        Dir N = Dir.N;
        Dir NE = Dir.NE;
        Dir W = Dir.W;
        Dir E = Dir.E;
        Dir SW = Dir.SW;
        Dir S = Dir.S;
        Dir SE = Dir.SE;
        while (!points.isEmpty()) {
            putPoints(newList, corner1, c1Random, points, NW, N, NE, W, E, SW, S, SE);
            putPoints(newList, corner2, c2Random, points, NE, N, NW, E, W, SE, S, SW);
            putPoints(newList, corner3, c3Random, points, SW, S, SE, W, E, NW, N, NE);
            putPoints(newList, corner4, c4Random, points, SE, S, SW, E, W, NE, N, NW);
        }
        return newList;
    }

    public static enum Dir {
        NW(-1, -1), N(0, -1), NE(1, -1), W(-1, 0), E(1, 0), SW(-1, 1), S(0, 1), SE(1, 1);
        final int dx, dy;

        private Dir(int dx, int dy) {
            this.dx = dx;
            this.dy = dy;
        }

        public Point add(Point p) {
            return new Point(p.x + dx, p.y + dy);
        }
    }

    public static void putPoints(List<Point> newList, List<Point> listToAddTo, Random rand,
                                 HashSet<Point> points, Dir... adj) {
        List<Point> newPoints = new LinkedList<>();
        for (Iterator<Point> iter = listToAddTo.iterator(); iter.hasNext();) {
            Point p = iter.next();
            Point pul = adj[0].add(p);
            Point pu = adj[1].add(p);
            Point pur = adj[2].add(p);
            Point pl = adj[3].add(p);
            Point pr = adj[4].add(p);
            Point pbl = adj[5].add(p);
            Point pb = adj[6].add(p);
            Point pbr = adj[7].add(p);
            int allChosen = 0;
            if (points.contains(pul)) {
                if (rand.nextInt(5) == 0) {
                    allChosen++;
                    newPoints.add(pul);
                    newList.add(pul);
                    points.remove(pul);
                }
            } else {
                allChosen++;
            }
            if (points.contains(pu)) {
                if (rand.nextInt(5) == 0) {
                    allChosen++;
                    newPoints.add(pu);
                    newList.add(pu);
                    points.remove(pu);
                }
            } else {
                allChosen++;
            }
            if (points.contains(pur)) {
                if (rand.nextInt(3) == 0) {
                    allChosen++;
                    newPoints.add(pur);
                    newList.add(pur);
                    points.remove(pur);
                }
            } else {
                allChosen++;
            }
            if (points.contains(pl)) {
                if (rand.nextInt(5) == 0) {
                    allChosen++;
                    newPoints.add(pl);
                    newList.add(pl);
                    points.remove(pl);
                }
            } else {
                allChosen++;
            }
            if (points.contains(pr)) {
                if (rand.nextInt(2) == 0) {
                    allChosen++;
                    newPoints.add(pr);
                    newList.add(pr);
                    points.remove(pr);
                }
            } else {
                allChosen++;
            }
            if (points.contains(pbl)) {
                if (rand.nextInt(5) == 0) {
                    allChosen++;
                    newPoints.add(pbl);
                    newList.add(pbl);
                    points.remove(pbl);
                }
            } else {
                allChosen++;
            }
            if (points.contains(pb)) {
                if (rand.nextInt(3) == 0) {
                    allChosen++;
                    newPoints.add(pb);
                    newList.add(pb);
                    points.remove(pb);
                }
            } else {
                allChosen++;
            }
            if (points.contains(pbr)) {
                newPoints.add(pbr);
                newList.add(pbr);
                points.remove(pbr);
            }
            if (allChosen == 7) {
                iter.remove();
            }
        }
        listToAddTo.addAll(newPoints);
    }

    public static List<MInteger> getColors(BufferedImage img) {
        int width = img.getWidth();
        int height = img.getHeight();
        List<MInteger> colors = new ArrayList<>(width * height);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                colors.add(new MInteger(img.getRGB(x, y)));
            }
        }
        return colors;
    }

    public static int search(MInteger color) {
        int rgbIndex = binarySearch(rgbList, color, rgb);
        int rbgIndex = binarySearch(rbgList, color, rbg);
        int grbIndex = binarySearch(grbList, color, grb);
        int gbrIndex = binarySearch(gbrList, color, gbr);
        int brgIndex = binarySearch(brgList, color, brg);
        int bgrIndex = binarySearch(bgrList, color, bgr);

        double distRgb = dist(rgbList.get(rgbIndex), color);
        double distRbg = dist(rbgList.get(rbgIndex), color);
        double distGrb = dist(grbList.get(grbIndex), color);
        double distGbr = dist(gbrList.get(gbrIndex), color);
        double distBrg = dist(brgList.get(brgIndex), color);
        double distBgr = dist(bgrList.get(bgrIndex), color);

        double minDist = Math.min(Math.min(Math.min(Math.min(Math.min(
                distRgb, distRbg), distGrb), distGbr), distBrg), distBgr);

        MInteger ans;
        if (minDist == distRgb) {
            ans = rgbList.get(rgbIndex);
        } else if (minDist == distRbg) {
            ans = rbgList.get(rbgIndex);
        } else if (minDist == distGrb) {
            ans = grbList.get(grbIndex);
        } else if (minDist == distGbr) {
            ans = grbList.get(grbIndex);
        } else if (minDist == distBrg) {
            ans = grbList.get(rgbIndex);
        } else {
            ans = grbList.get(grbIndex);
        }
        rgbList.remove(ans);
        rbgList.remove(ans);
        grbList.remove(ans);
        gbrList.remove(ans);
        brgList.remove(ans);
        bgrList.remove(ans);
        return ans.val;
    }

    public static int binarySearch(List<MInteger> list, MInteger val, Comparator<MInteger> cmp){
        int index = Collections.binarySearch(list, val, cmp);
        if (index < 0) {
            index = ~index;
            if (index >= list.size()) {
                index = list.size() - 1;
            }
        }
        return index;
    }

    public static double dist(MInteger color1, MInteger color2) {
        int c1 = color1.val;
        int r1 = (c1 & 0xFF0000) >> 16;
        int g1 = (c1 & 0x00FF00) >> 8;
        int b1 = (c1 & 0x0000FF);

        int c2 = color2.val;
        int r2 = (c2 & 0xFF0000) >> 16;
        int g2 = (c2 & 0x00FF00) >> 8;
        int b2 = (c2 & 0x0000FF);

        int dr = r1 - r2;
        int dg = g1 - g2;
        int db = b1 - b2;
        return Math.sqrt(dr * dr + dg * dg + db * db);
    }

    //This method is here solely for my ease of use (I put the files under <Project Name>/Resources/ )
    public static File resource(String fileName) {
        return new File(System.getProperty("user.dir") + "/Resources/" + fileName);
    }

    static List<MInteger> rgbList;
    static List<MInteger> rbgList;
    static List<MInteger> grbList;
    static List<MInteger> gbrList;
    static List<MInteger> brgList;
    static List<MInteger> bgrList;
    static Comparator<MInteger> rgb = (color1, color2) -> color1.val - color2.val;
    static Comparator<MInteger> rbg = (color1, color2) -> {
        int c1 = color1.val;
        int c2 = color2.val;
        c1 = ((c1 & 0xFF0000)) | ((c1 & 0x00FF00) >> 8) | ((c1 & 0x0000FF) << 8);
        c2 = ((c2 & 0xFF0000)) | ((c2 & 0x00FF00) >> 8) | ((c2 & 0x0000FF) << 8);
        return c1 - c2;
    };
    static Comparator<MInteger> grb = (color1, color2) -> {
        int c1 = color1.val;
        int c2 = color2.val;
        c1 = ((c1 & 0xFF0000) >> 8) | ((c1 & 0x00FF00) << 8) | ((c1 & 0x0000FF));
        c2 = ((c2 & 0xFF0000) >> 8) | ((c2 & 0x00FF00) << 8) | ((c2 & 0x0000FF));
        return c1 - c2;
    };

    static Comparator<MInteger> gbr = (color1, color2) -> {
        int c1 = color1.val;
        int c2 = color2.val;
        c1 = ((c1 & 0xFF0000) >> 16) | ((c1 & 0x00FF00) << 8) | ((c1 & 0x0000FF) << 8);
        c2 = ((c2 & 0xFF0000) >> 16) | ((c2 & 0x00FF00) << 8) | ((c2 & 0x0000FF) << 8);
        return c1 - c2;
    };

    static Comparator<MInteger> brg = (color1, color2) -> {
        int c1 = color1.val;
        int c2 = color2.val;
        c1 = ((c1 & 0xFF0000) >> 8) | ((c1 & 0x00FF00) >> 8) | ((c1 & 0x0000FF) << 16);
        c2 = ((c2 & 0xFF0000) >> 8) | ((c2 & 0x00FF00) >> 8) | ((c2 & 0x0000FF) << 16);
        return c1 - c2;
    };

    static Comparator<MInteger> bgr = (color1, color2) -> {
        int c1 = color1.val;
        int c2 = color2.val;
        c1 = ((c1 & 0xFF0000) >> 16) | ((c1 & 0x00FF00)) | ((c1 & 0x0000FF) << 16);
        c2 = ((c2 & 0xFF0000) >> 16) | ((c2 & 0x00FF00)) | ((c2 & 0x0000FF) << 16);
        return c1 - c2;
    };

    public static void validate(BufferedImage palette, BufferedImage result) {
        List<Integer> paletteColors = getTrueColors(palette);
        List<Integer> resultColors = getTrueColors(result);
        Collections.sort(paletteColors);
        Collections.sort(resultColors);
        System.out.println(paletteColors.equals(resultColors));
    }

    public static List<Integer> getTrueColors(BufferedImage img) {
        int width = img.getWidth();
        int height = img.getHeight();
        List<Integer> colors = new ArrayList<>(width * height);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                colors.add(img.getRGB(x, y));
            }
        }
        Collections.sort(colors);
        return colors;
    }
}

වර්ණ ත්‍රිමාණ බැවින් 3-අවකාශය තුළ සෑම පික්සෙල් එකකටම ආසන්නතම වර්ණය (හොඳයි, බොහෝ විට ආසන්නතම) සොයා ගැනීමෙන් මගේ ප්‍රවේශය ක්‍රියාත්මක වේ.

මෙය ක්‍රියාත්මක වන්නේ අපට පිරවිය යුතු සියලුම කරුණු ලැයිස්තුවක් සහ අපට භාවිතා කළ හැකි සියලු වර්ණ ලැයිස්තුවක් නිර්මාණය කිරීමෙනි. අපි ලකුණු ලැයිස්තුව අහඹු ලෙස සකසමු (එබැවින් රූපය වඩා හොඳ වනු ඇත), ඉන්පසු අපි එක් එක් ලක්ෂ්‍යය හරහා ගොස් ප්‍රභව රූපයේ වර්ණය ලබා ගනිමු.

යාවත්කාලීන කිරීම: මම හුදෙක් ද්විමය සෙවුමකට පුරුදුව සිටියෙමි, එබැවින් රතු පාටට වඩා කොළ පාටට වඩා නිල් පැහැයට වඩා ගැලපේ. මම දැන් එය ද්විමය සෙවුම් හයක් කිරීමට (වෙනස් කළ හැකි සියලු ප්‍රේරණයන්) වෙනස් කර, ආසන්නතම වර්ණය තෝරන්න. එය ගත වන්නේ ~ 6 ගුණයක් (එනම් මිනිත්තු 1) පමණි. පින්තූර තවමත් ධාන්යමය වුවත්, වර්ණ වඩා හොඳින් ගැලපේ.

යාවත්කාලීන 2: මම තවදුරටත් ලැයිස්තුව අහඹු ලෙස සකසන්නේ නැත. ඒ වෙනුවට, මම තුනෙන් එකක නියමය අනුගමනය කරමින් ලකුණු 4 ක් තෝරාගෙන, අහඹු ලෙස ලකුණු සකස් කර, කේන්ද්‍රය පිරවීමට වැඩි කැමැත්තක් දක්වමි.

සටහන: පැරණි පින්තූර සඳහා සංශෝධන ඉතිහාසය බලන්න.

මොනා ලීසා -> ගඟ:

රූප විස්තරය මෙහි ඇතුළත් කරන්න

මොනා ලීසා -> ඇමරිකානු ගොතික්:

රූප විස්තරය මෙහි ඇතුළත් කරන්න

මොනා ලීසා -> රේට්‍රාස්ඩ් ගෝලා:

රූප විස්තරය මෙහි ඇතුළත් කරන්න

තරු රාත්‍රිය -> මොනා ලීසා:

රූප විස්තරය මෙහි ඇතුළත් කරන්න


රූපය සාදන ලද ආකාරය පෙන්වන සජීවිකරණ Gif මෙන්න:

රූප විස්තරය මෙහි ඇතුළත් කරන්න

මොනා ලිසා වෙතින් ලබාගත් පික්සෙල් පෙන්වයි:

රූප විස්තරය මෙහි ඇතුළත් කරන්න


11
ඒක හරිම පුදුමයි. මම හිතුවේ නැහැ ඒක වෙන්න පුළුවන් කියලා.
ඇන්ඩෝඩාන්

6
එය කිරීම සුළුපටු දෙයක් යැයි මට සැකයක් ඇත, නමුත් පික්සෙල් මුල් රූපයේ සිට අවසාන රූපයට නැවත ස්ථානගත වන බව පෙන්වන සජීවිකරණ අනුවාදයක් නිෂ්පාදනය කිරීමට හැකිවීම පුදුම සහගතය.
මිලිනන්

2
මම හිතන්නේ ඔබ ගැටලුව වරදවා වටහා ගත්තා. පිටපත නිර්මාණය කිරීම සඳහා ඔබට පික්සෙල් නැවත සකස් කළ යුතුය, හුදෙක් වර්ණාලේපයේ වර්ණ භාවිතා නොකරන්න. සෑම වෙනස් වර්ණයක්ම පිටපතෙහි හරියටම එකම වාර ගණනක් දර්ශනය විය යුතුය. ඔබේ පින්තූර මගේ පිටපත පසු කරන්නේ නැත.
කැල්වින්ගේ විනෝදාංශ

7
@ ක්වින්කන්ක්ස් පෙනෙන පරිදි මගේ පිටපත නිවැරදි විය (මම එය පසු පරම්පරාව සඳහා සරල කළද) සහ ඔබේ වැඩසටහනද එසේමය. හේතු නිසා මොනා ලිසා රූපය උඩුගත කරන විට එය තරමක් වෙනස් වී ඇති බව මට විශ්වාස නැත. (177, 377) හි ඇති පික්සෙල් මාර්ගගතව (0, 0, 16) මාර්ගගතව සහ (0, 0, 14) මගේ නිවසේ පරිගණකයේ ඇති බව මම දුටුවෙමි. නැතිවූ ගොනු වර්ගයක් සමඟ ඇති ගැටළු මඟහරවා ගැනීම සඳහා මම jpegs pngs සමඟ ආදේශ කර ඇත්තෙමි. පින්තූරවල ඇති පික්සල් දත්ත වෙනස් නොවිය යුතු නමුත් රූප නැවත බාගත කිරීම නුවණට හුරුය.
කැල්වින්ගේ විනෝදාංශ

8
මෙය වඩාත්ම ජනප්‍රිය පිළිතුර නොවිය යුතුය. ඇල්ගොරිතම අනවශ්‍ය ලෙස සංකීර්ණ වන අතර ප්‍රති results ල නරක වුවත් ඒවා සිත්ගන්නාසුලුය. ආර්ඩිට්සුගේ ප්‍රති result ලය සමඟ මොනා ලිසා සිට රේට්‍රාස් කරන ලද ගෝල දක්වා වූ පරිවර්තනය සංසන්දනය කරන්න: i.stack.imgur.com/WhVcO.png
ලීෆ්

99

පර්ල්, විද්‍යාගාර වර්ණ අවකාශය සහ වියළීම

සටහන: දැන් මට සී විසඳුමක් ද තිබේ.

ප්‍රධාන වැඩිදියුණු කිරීම් දෙකක් සහිතව, ඇඩිට්සුගේ සමාන ප්‍රවේශයක් භාවිතා කරයි, (අහඹු ස්ථාන දෙකක් තෝරන්න, සහ එම ස්ථානය ඉලක්ක පිංතූරයට සමාන කරයි නම් එම ස්ථානවල පික්සෙල් මාරු කරන්න), ප්‍රධාන වැඩිදියුණු කිරීම් දෙකක් සමඟ:

  1. වර්ණ සංසන්දනය කිරීම සඳහා CIE L a b * වර්ණ අවකාශයක් භාවිතා කරයි - මෙම අවකාශයේ ඇති යුක්ලීඩියානු මෙට්‍රික් යනු වර්ණ දෙකක් අතර ප්‍රත්‍යක්‍ෂමය වෙනස සඳහා ඉතා හොඳ දළ විශ්ලේෂණයකි, එබැවින් වර්ණ සිතියම් RGB හෝ HSV / HSL වලට වඩා නිවැරදි විය යුතුය.
  2. ආරම්භක මුරපදයකින් පික්සෙල් හොඳම තනි ස්ථානයක තැබීමෙන් පසුව, එය අහඹු ලෙස වියළීමකින් අතිරේක පාස් එකක් කරයි. හුවමාරු ස්ථාන දෙකෙහි පික්සල් අගයන් සංසන්දනය කරනවා වෙනුවට, එය 3x3 අසල්වැසි සාමාන්‍ය පික්සල් අගය ගණනය කරනුයේ swap ස්ථාන කේන්ද්‍ර කර ගනිමිනි. හුවමාරුවක් අසල්වැසි ප්‍රදේශවල සාමාන්‍ය වර්ණ වැඩි දියුණු කරන්නේ නම්, එය තනි පික්සෙල් අඩු නිරවද්‍යතාවයක් ලබා දුන්නද එයට අවසර ඇත. සමහර රූප යුගල සඳහා මෙය ගුණාත්මකභාවය කෙරෙහි සැක සහිත බලපෑමක් ඇති කරයි (සහ පලත් ආචරණය අඩු කැපී පෙනේ), නමුත් සමහර අයට (ගෝලාකාර -> ඕනෑම දෙයක් වැනි) එය තරමක් උපකාරී වේ. "විස්තර" සාධකය මධ්‍යම පික්සෙල් විචල්‍ය මට්ටමකට අවධාරණය කරයි. එය වැඩි කිරීමෙන් සමස්ත ඩිටර් ප්‍රමාණය අඩු වන නමුත් ඉලක්ක රූපයෙන් වඩාත් සියුම් තොරතුරු රඳවා ගනී. වියළී ගිය ප්‍රශස්තිකරණය මන්දගාමී වේ,

සාමාන්‍ය විද්‍යාගාර අගයන්, ඩිටර් මෙන් ඇත්ත වශයෙන්ම යුක්ති සහගත නොවේ (ඒවා XYZ බවට පරිවර්තනය කළ යුතුය, සාමාන්‍යය සහ ආපසු පරිවර්තනය කළ යුතුය) නමුත් මෙම අරමුණු සඳහා එය හොඳින් ක්‍රියාත්මක වේ.

මෙම පින්තූරවල අවසන් කිරීමේ සීමාවන් 100 සහ 200 ක් ඇත (හුවමාරුව 5000 න් 1 ට වඩා අඩු වූ විට පළමු අදියර අවසන් කරන්න, දෙවන අදියර 2500 දී 1 ට අවසන් වේ), සහ 12 ක විචලනය වන සවිස්තරාත්මක සාධකය (පෙර කට්ටලයට වඩා ටිකක් තද විය ). මෙම සුපිරි උසස් තත්ත්වයේ සැකසුමකදී, රූප ජනනය කිරීමට බොහෝ කාලයක් ගත වේ, නමුත් සමාන්තරකරණයෙන් මගේ කාර්යය 6-කොටුව මත පැයක් ඇතුළත අවසන් වේ. මිනිත්තු 500 ක් ඇතුළත අගයන් 500 ක් හෝ ඊට වැඩි ගණනක් ඉහළට ඔසවා තැබීමෙන් ඒවා මඳක් ඔප දැමූ බවක් පෙනේ. මට අවශ්‍ය වූයේ ඇල්ගොරිතම මෙහි හොඳම දේ පෙන්වීමටයි.

කේතය කිසිසේත් ලස්සන නැත:

#!/usr/bin/perl
use strict;
use warnings;
use Image::Magick;
use Graphics::ColorObject 'RGB_to_Lab';
use List::Util qw(sum max);

my $source = Image::Magick->new;
$source->Read($ARGV[0]);
my $target = Image::Magick->new;
$target->Read($ARGV[1]);
my ($limit1, $limit2, $detail) = @ARGV[2,3,4];

my ($width, $height) = ($target->Get('width'), $target->Get('height'));

# Transfer the pixels of the $source onto a new canvas with the diemnsions of $target
$source->Set(magick => 'RGB');
my $img = Image::Magick->new(size => "${width}x${height}", magick => 'RGB', depth => 8);
$img->BlobToImage($source->ImageToBlob);

my ($made, $rejected) = (0,0);

system("rm anim/*.png");

my (@img_lab, @target_lab);
for my $x (0 .. $width) {
  for my $y (0 .. $height) {
    $img_lab[$x][$y] = RGB_to_Lab([$img->getPixel(x => $x, y => $y)], 'sRGB');
    $target_lab[$x][$y] = RGB_to_Lab([$target->getPixel(x => $x, y => $y)], 'sRGB');
  }
}

my $n = 0;
my $frame = 0;
my $mode = 1;

while (1) {
  $n++;

  my $swap = 0;
  my ($x1, $x2, $y1, $y2) = (int rand $width, int rand $width, int rand $height, int rand $height);
  my ($dist, $dist_swapped);

  if ($mode == 1) {
    $dist = (sum map { ($img_lab[$x1][$y1][$_] - $target_lab[$x1][$y1][$_])**2 } 0..2)
          + (sum map { ($img_lab[$x2][$y2][$_] - $target_lab[$x2][$y2][$_])**2 } 0..2);

    $dist_swapped = (sum map { ($img_lab[$x2][$y2][$_] - $target_lab[$x1][$y1][$_])**2 } 0..2)
                  + (sum map { ($img_lab[$x1][$y1][$_] - $target_lab[$x2][$y2][$_])**2 } 0..2);

  } else { # dither mode
    my $xoffmin = ($x1 == 0 || $x2 == 0 ? 0 : -1);
    my $xoffmax = ($x1 == $width - 1 || $x2 == $width - 1 ? 0 : 1);
    my $yoffmin = ($y1 == 0 || $y2 == 0 ? 0 : -1);
    my $yoffmax = ($y1 == $height - 1 || $y2 == $height - 1 ? 0 : 1);

    my (@img1, @img2, @target1, @target2, $points);
    for my $xoff ($xoffmin .. $xoffmax) {
      for my $yoff ($yoffmin .. $yoffmax) {
        $points++;
        for my $chan (0 .. 2) {
          $img1[$chan] += $img_lab[$x1+$xoff][$y1+$yoff][$chan];
          $img2[$chan] += $img_lab[$x2+$xoff][$y2+$yoff][$chan];
          $target1[$chan] += $target_lab[$x1+$xoff][$y1+$yoff][$chan];
          $target2[$chan] += $target_lab[$x2+$xoff][$y2+$yoff][$chan];
        }
      }
    }

    my @img1s = @img1;
    my @img2s = @img2;
    for my $chan (0 .. 2) {
      $img1[$chan] += $img_lab[$x1][$y1][$chan] * ($detail - 1);
      $img2[$chan] += $img_lab[$x2][$y2][$chan] * ($detail - 1);

      $target1[$chan] += $target_lab[$x1][$y1][$chan] * ($detail - 1);
      $target2[$chan] += $target_lab[$x2][$y2][$chan] * ($detail - 1);

      $img1s[$chan] += $img_lab[$x2][$y2][$chan] * $detail - $img_lab[$x1][$y1][$chan];
      $img2s[$chan] += $img_lab[$x1][$y1][$chan] * $detail - $img_lab[$x2][$y2][$chan];
    }

    $dist = (sum map { ($img1[$_] - $target1[$_])**2 } 0..2)
          + (sum map { ($img2[$_] - $target2[$_])**2 } 0..2);

    $dist_swapped = (sum map { ($img1s[$_] - $target1[$_])**2 } 0..2)
                  + (sum map { ($img2s[$_] - $target2[$_])**2 } 0..2);

  }

  if ($dist_swapped < $dist) {
    my @pix1 = $img->GetPixel(x => $x1, y => $y1);
    my @pix2 = $img->GetPixel(x => $x2, y => $y2);
    $img->SetPixel(x => $x1, y => $y1, color => \@pix2);
    $img->SetPixel(x => $x2, y => $y2, color => \@pix1);
    ($img_lab[$x1][$y1], $img_lab[$x2][$y2]) = ($img_lab[$x2][$y2], $img_lab[$x1][$y1]);
    $made ++;
  } else {
    $rejected ++;
  }

  if ($n % 50000 == 0) {
#    print "Made: $made Rejected: $rejected\n";
    $img->Write('png:out.png');
    system("cp", "out.png", sprintf("anim/frame%05d.png", $frame++));
    if ($mode == 1 and $made < $limit1) {
      $mode = 2;
      system("cp", "out.png", "nodither.png");
    } elsif ($mode == 2 and $made < $limit2) {
      last;
    }
    ($made, $rejected) = (0, 0);
  }
}

ප්රතිපල

ඇමරිකානු ගොතික් පලත්

වියළීම හෝ නොකිරීම සමඟ මෙහි සුළු වෙනසක් ඇත.

මොනා ලීසා පලත්

වියළීම ගෝලාකාරයන්හි බන්ධනය අඩු කරයි, නමුත් විශේෂයෙන් ලස්සන නොවේ.

තරු රාත්‍රී පලත්

මොනා ලීසා මඳක් වැඩි විස්තරයක් රඳවා තබා ගනී. ගෝලාකාර යනු අවසන් වරට සමාන තත්වයකි.

කෑගැසීමේ පලත්

තාරුණ්‍යයෙන් තොර තරු රාත්‍රිය මෙතෙක් සිදු වූ භයානකම දෙයයි. වියළීම එය වඩාත් ඡායාරූප-නිරවද්‍ය, නමුත් වඩා රසවත් නොවේ.

ගෝලාකාර පලත්

ඇඩිට්සු පවසන පරිදි සත්‍ය පරීක්ෂණය. මම හිතන්නේ මම සමත් වෙනවා.

ඇමරිකානු ගොතික් සහ මොනා ලිසා සමඟ ඩිටරින් කිරීම බෙහෙවින් උපකාරී වන අතර, අළු සහ වෙනත් වර්ණ වඩාත් තීව්‍ර පික්සෙල් සමඟ මිශ්‍ර කර භයානක පැල්ලම් වෙනුවට අර්ධ නිරවද්‍ය සම නාද නිපදවයි. කෑගැසීම බලපාන්නේ ඊට වඩා අඩුවෙන්.

කැමරෝ - මුස්තැන්ග්

දෝෂ සටහනෙන් මූලාශ්‍ර රූප.

කැමරෝ:

මුස්තැන්ග්:

කැමරෝ පලත්

නොපෙනී යයි.

"තද" වියළීම (ඉහත විස්තරාත්මක සාධකය) බොහෝ වෙනස් නොවේ, හුඩ් සහ වහලයේ උද්දීපනයන්හි සුළු විස්තරයක් එක් කරයි.

“ලිහිල්” ඩිටර් (සවිස්තරාත්මක සාධකය 6 දක්වා පහත වැටී ඇත) සැබවින්ම නාදය සුමට කරයි, සහ වැඩි විස්තර වින්ඩ්ෂීල්ඩ් හරහා දැකිය හැකි නමුත් සෑම තැනකම ඩිටර්න්ග් රටා වඩාත් පැහැදිලිව පෙනේ.

මුස්තැන්ග් පලත්

මෝටර් රථයේ කොටස් විශිෂ්ට පෙනුමක් ඇති නමුත් අළු පික්සල් දිලිසෙන පෙනුමක්. නරකම දෙය නම්, තද කහ පැහැති පික්සෙල් සියල්ලම රතු කැමරෝ සිරුර පුරා බෙදා හැර ඇති අතර, නොකැඩෙන ඇල්ගොරිතමයට සැහැල්ලු ඒවා සමඟ කිසිදු සම්බන්ධයක් සොයාගත නොහැක (ඒවා මෝටර් රථයට ගෙනයාම තරගය නරක අතට හැරෙනු ඇති අතර ඒවා වෙනත් ස්ථානයකට ගෙන යයි පසුබිමෙහි ස්ථානය ශුද්ධ වෙනසක් නොකරයි), එබැවින් පසුබිමේ අවතාරයක්-මුස්තැන්ග් ඇත.

ඩිටර් කිරීම මඟින් එම අමතර කහ පික්සල් අවට පැතිරීමට හැකි වන අතර එමඟින් ඒවා ස්පර්ශ නොවන අතර ඒවා ක්‍රියාවලියේ පසුබිම පුරා වැඩි හෝ අඩු ඒකාකාරව විසුරුවා හරිනු ලැබේ. මෝටර් රථයේ උද්දීපනයන් සහ සෙවනැලි ටිකක් හොඳ පෙනුමක්.

නැවතත්, ලිහිල් ඩිටර් එකෙහි ඒකාකාර නාදයක් ඇති අතර, හෙඩ් ලයිට් සහ වින්ඩ්ෂීල්ඩ් පිළිබඳ වැඩි විස්තර හෙළි කරයි. මෝටර් රථය නැවතත් පාහේ රතු පැහැයෙන් පෙනේ. කිසියම් හේතුවක් නිසා පසුබිම ක්ලම්පියර් ය. මම එයට කැමති දැයි විශ්වාස නැත.

වීඩියෝ

( මූලස්ථාන සබැඳිය )


3
මම මේකට ඇත්තටම කැමතියි, දැඩි ලෙස වියළී ගිය රූපවලට පුදුමාකාර ලෙස අර්ථවත් හැඟීමක් ඇත. සයුරත් මොනා ලීසා කවුරුන් හෝ සිටීද?
බොරිස් ද ස්පයිඩර්

2
ඔබේ ඇල්ගොරිතම නිසැකවම භයානක ගෝලාකාර පැලේට් සමඟ හොඳ කාර්යයක් කරයි, හොඳ වැඩක්!
ස්නෝබොඩි

1
ob හොබ්ස් දේදුන්න තාලයේ අපූරු භාවිතය, සහ ඔබේ මෝටර් රථ පරිපූර්ණයි! මගේ සජීවිකරණ ස්ක්‍රිප්ට් ප්‍රදර්ශනය කිරීම සඳහා යූ ටියුබ් වීඩියෝවක් තුළ ඔබගේ සමහර පින්තූර භාවිතා කළහොත් එය හරිද?
කැල්වින්ගේ විනෝදාංශ

1
මම හිතන්නේ ඔබේ වියළීම එම රටාව ලබා දීමට එකම හේතුව වන්නේ ඔබ 3x3 පික්සල් බ්ලොක් එකක් භාවිතා කරන නිසා බර සමඟ කේන්ද්‍රය සඳහා පමණක් වෙනස් කර ඇති බවයි. ඔබ කේන්ද්‍රයේ සිට ඇති දුර අනුව පික්සෙල් බර කිරා බැලුවහොත් (එම නිසා කෙළවරේ පික්සෙල් යාබද 4 ට වඩා අඩු දායකත්වයක් සපයයි) සහ තරමක් වැඩි පික්සල් දක්වා විහිදේ නම්, වියළීම සැලකිය යුතු තරම් අඩු විය යුතුය. එය දැනටමත් දේදුන්න තාලයට එතරම් විශාල දියුණුවක් ලබා දී ඇති බැවින් එයට තවත් කුමක් කළ හැකිදැයි බැලීමට වටිනවා විය හැකිය ...
ට්‍රයිකොප්ලැක්ස්

1
ithithubphagocyte මම දින භාගයක් ඒ වගේ දේවල් අත්හදා බැලුවා, නමුත් ඒ කිසිවක් මට අවශ්‍ය ආකාරය සාර්ථක කරගත්තේ නැහැ. එක් ප්‍රභේදයක් ඉතා අහඹු පෙනුමක් ඇති ඩිටර් එකක් නිපදවූ අතර එය කිසි විටෙකත් අවසන් නොවූ ප්‍රශස්තිකරණ අවධියක් මට ලබා දුන්නේය. වෙනත් ප්‍රභේදවලට වඩා නරක කෞතුක වස්තු හෝ ශක්තිමත් වියළී යාමක් තිබුණි. ඉමේජ් මැජික්ගේ ස්ප්ලයින් අන්තර් මැදිහත්වීමට ස්තූතිවන්ත වන පරිදි මගේ සී විසඳුම වඩා හොඳ විය. එය 5 නක රේඛාවක් බැවින් 5x5 අසල්වැසි ප්‍රදේශයක් භාවිතා කරන බව මම සිතමි.
හොබ්ස්

80

පයිතන්

අදහස සරලයි: සෑම පික්සෙල් එකකටම ත්‍රිමාණ RGB අවකාශයේ ලක්ෂ්‍යයක් ඇත. ඉලක්කය වන්නේ එක් එක් ප්‍රභවයේ පික්සෙල් එකකට සහ ගමනාන්ත රූපයට ගැලපීමයි, වඩාත් සුදුසු ඒවා 'සමීප' විය යුතුය ('එකම' වර්ණය නියෝජනය කරන්න). ඒවා එකිනෙකට වෙනස් ආකාරවලින් බෙදා හැරිය හැකි බැවින්, අපට ළඟම ඇති අසල්වැසියා සමඟ සැසඳිය නොහැක.

උපාය

ඉඩ nයනු පූර්ණ සංඛ්යාවකි (කුඩා, 3-255 හෝ එසේ) විය. දැන් RGB අවකාශයේ ඇති පික්සෙල් ක්ලවුඩ් පළමු අක්ෂය (R) අනුව වර්ග කෙරේ. මෙම පික්සෙල් කට්ටලය දැන් n කොටස් වලට බෙදා ඇත. සෑම කොටසක්ම දැන් දෙවන අක්ෂය (බී) ඔස්සේ වර්ග කර ඇති අතර එය නැවත කොටස් කර ඇති ආකාරයටම වර්ග කර ඇත. අපි මෙය පින්තූර දෙකෙන්ම කරන අතර, දැන් ලකුණු දෙකටම තිබේ. දැන් අපට අරාවෙහි ඇති පිහිටීම අනුව පික්සෙල් සමඟ සැසඳිය හැකිය, එක් එක් අරාවෙහි එකම ස්ථානයක ඇති පික්සෙල් එකකට RGB අවකාශයේ ඇති සෑම පික්සල් ක්ලවුඩ් වලට සාපේක්ෂව සමාන ස්ථානයක් ඇත.

රූප දෙකෙහිම RGB අවකාශයේ පික්සෙල් බෙදා හැරීම සමාන නම් (එයින් අදහස් වන්නේ මාරුවීම සහ / හෝ අක්ෂ 3 දිගේ දිගු කිරීම පමණි) ප්‍රති result ලය අනාවැකි කිව හැකි වනු ඇත. බෙදාහැරීම් සම්පූර්ණයෙන්ම වෙනස් ලෙස පෙනේ නම්, මෙම ඇල්ගොරිතම හොඳ ප්‍රති results ල ලබා නොදෙනු ඇත (අවසාන උදාහරණයෙන් පෙනෙන පරිදි) නමුත් මෙය මා සිතන අමාරු අවස්ථාවන්ගෙන් එකකි. එය නොකරන දෙය නම් සංජානනය තුළ අසල්වැසි පික්සෙල් අන්තර්ක්‍රියාකාරිත්වයේ බලපෑම් භාවිතා කිරීමයි.

කේතය

වියාචනය: මම පයිතන්ට නිරපේක්ෂ නවකයෙක්.

from PIL import Image

n = 5 #number of partitions per channel.

src_index = 3 #index of source image
dst_index = 2 #index of destination image

images =  ["img0.bmp","img1.bmp","img2.bmp","img3.bmp"];
src_handle = Image.open(images[src_index])
dst_handle = Image.open(images[dst_index])
src = src_handle.load()
dst = dst_handle.load()
assert src_handle.size[0]*src_handle.size[1] == dst_handle.size[0]*dst_handle.size[1],"images must be same size"

def makePixelList(img):
    l = []
    for x in range(img.size[0]):
        for y in range(img.size[1]):
            l.append((x,y))
    return l

lsrc = makePixelList(src_handle)
ldst = makePixelList(dst_handle)

def sortAndDivide(coordlist,pixelimage,channel): #core
    global src,dst,n
    retlist = []
    #sort
    coordlist.sort(key=lambda t: pixelimage[t][channel])
    #divide
    partitionLength = int(len(coordlist)/n)
    if partitionLength <= 0:
        partitionLength = 1
    if channel < 2:
        for i in range(0,len(coordlist),partitionLength):
            retlist += sortAndDivide(coordlist[i:i+partitionLength],pixelimage,channel+1)
    else:
        retlist += coordlist
    return retlist

print(src[lsrc[0]])

lsrc = sortAndDivide(lsrc,src,0)
ldst = sortAndDivide(ldst,dst,0)

for i in range(len(ldst)):
    dst[ldst[i]] = src[lsrc[i]]

dst_handle.save("exchange"+str(src_index)+str(dst_index)+".png")

ප්‍රති ult ලය

සරල විසඳුම සලකා බැලීමේදී එය නරක නැතැයි මම සිතමි. පරාමිතිය සමඟ නොගැලපෙන විට හෝ පළමුව වර්ණ වෙනත් වර්ණ අවකාශයක් බවට පරිවර්තනය කිරීමේදී හෝ කොටස් කිරීම ප්‍රශස්ත කිරීමේදී ඔබට වඩා හොඳ ප්‍රති results ල ලබා ගත හැකිය.

මගේ ප්‍රති .ල සංසන්දනය කිරීම

සම්පූර්ණ ගැලරිය මෙතැන: https://imgur.com/a/hzaAm#6

ගංගාව සඳහා සවිස්තරාත්මක

monalisa> ගඟ

monalisa> ගඟ

මිනිස්සු> ගඟ

මිනිස්සු> ගඟ

බෝල> ගඟ

බෝල> ගඟ

තරු රාත්‍රිය> ගඟ

nocturne> ගඟ

අ cry න> ගඟ

thecry> ගඟ

බෝල> මොනාලිසා, වෙනස් n = 2,4,6, ..., 20

මෙය මා සිතන වඩාත්ම අභියෝගාත්මක කර්තව්‍යයයි, ලස්සන පින්තූරවලට වඩා, මෙහි වෙනස් පරාමිති අගයන් n = 2,4,6, ..., 20 හි gif එකක් (වර්ණ 256 දක්වා අඩු කළ යුතුව තිබුණි). මට නම් ඉතා අඩු අගයන් වඩා හොඳ රූප නිපදවීම පුදුම සහගතය (Mme. Lisa ගේ මුහුණ දෙස බලන විට): බෝල> මොනාලිසා

කණගාටුයි මට නවත්වන්න බැහැ

ඔබ වඩා හොඳට කැමති කුමන එකද? චෙවි කැමරෝ හෝ ෆෝඩ් මස්ටෑන්ග්? සමහර විට මෙම තාක්ෂණය වැඩිදියුණු කර bw පින්තූර වර්ණ ගැන්වීම සඳහා භාවිතා කළ හැකිය. දැන් මෙහි: පළමුව මම මෝටර් රථ පසුබිමෙන් දළ වශයෙන් සුදු පැහැයෙන් පින්තාරු කර (තීන්ත වලින්, ඉතා වෘත්තීයමය නොවේ ...) ඉන්පසු සෑම දිශාවකටම පයිතන් වැඩසටහන භාවිතා කළෙමි.

මුල්

මුල් මුල්

නැවත මතක් විය

සමහර කෞතුක වස්තු තිබේ, මම සිතන්නේ එක් මෝටර් රථයක ප්‍රමාණය අනෙක් මෝටර් රථයට වඩා තරමක් විශාල වූ නිසාත්, මගේ කලා කුසලතා නරක නිසාත් =) හැසිරවීම රූප විස්තරය මෙහි ඇතුළත් කරන්න


5
වාව්, මම ඇත්තටම ස්ටාර්රි නයිට් ගඟට ආදරෙයි, සහ කෑගැසීම එය ගිනි ගංගාවක් මෙන් පෙනෙන්නේ කෙසේද.
කැල්වින්ගේ විනෝදාංශ

@ කැල්වින්ගේ විනෝදාංශය ඔව්! ඔවුන් බොහෝ දුරට ඇදී ගොස් ඇති බවක් පෙනේ, මම නව රූප උඩුගත කිරීමේ කාර්යබහුල බැවින් මම ඔවුන් දෙස සමීපව බැලුවේ නැත = P නමුත් මෙම විශාල අභියෝගයට ස්තූතියි!
දෝෂය

3
මම කාර් පරිණාමනයන්ට කැමතියි. මෙය වරක් යම් ආකාරයක රූප සංස්කරණ පරිවර්තනයක් බවට පත්විය හැකිය, ඇත්ත වශයෙන්ම!
ටොම්ස්මිං කිරීම

omstomsmeding ස්තූතියි, මම දැනටමත් b / w රූප වර්ණ ගැන්වීම සඳහා තාක්‍ෂණය භාවිතා කිරීම ගැන සිතුවෙමි, නමුත් මේ දක්වා සීමිත සාර්ථකත්වයක් ඇත. නමුත් සමහර විට අපට මෙය සිදු කිරීම සඳහා තවත් අදහස් කිහිපයක් අවශ්‍ය වේ =)
දෝෂය

laflawr මගේ සජීවිකරණ ස්ක්‍රිප්ට් ප්‍රදර්ශනය කිරීම සඳහා යූ ටියුබ් වීඩියෝවක් තුළ ඔබගේ පින්තූර කිහිපයක් භාවිතා කළහොත් එය හරිද?
කැල්වින්ගේ විනෝදාංශ

49

පයිතන් - න්‍යායාත්මකව ප්‍රශස්ත විසඳුමක්

න්‍යායාත්මකව ප්‍රශස්ත යැයි මම කියන්නේ සැබවින්ම ප්‍රශස්ත විසඳුම ගණනය කිරීමට තරම් ශක්‍ය නොවන බැවිනි. න්‍යායාත්මක විසඳුම විස්තර කිරීමෙන් මම ආරම්භ කරමි, පසුව අවකාශය හා වේලාව යන දෙකෙහිම එය පරිගණකමය වශයෙන් කළ හැකි වන පරිදි එය කරකැවූ ආකාරය පැහැදිලි කරමි.

පැරණි හා නව රූප අතර ඇති සියලුම පික්සෙල් හරහා අඩුම දෝෂය ලබා දෙන විසඳුම ලෙස මම වඩාත් ප්‍රශස්ත විසඳුම ලෙස සලකමි. පික්සල් දෙකක් අතර ඇති දෝෂය අර්ථ දැක්වෙන්නේ එක් එක් වර්ණ අගය (R, G, B) ඛණ්ඩාංකයක් වන ත්‍රිමාණ අවකාශයේ ලක්ෂ්‍ය අතර යුක්ලිඩියානු දුර ලෙස ය. ප්‍රායෝගිකව, මිනිසුන් දේවල් දකින ආකාරය නිසා, ප්‍රශස්ත විසඳුම හොඳම පෙනුමැති විසඳුම නොවිය හැකිය . කෙසේ වෙතත්, එය සෑම අවස්ථාවකම තරමක් හොඳින් කරන බව පෙනේ.

සිතියම්ගත කිරීම ගණනය කිරීම සඳහා, මෙය අවම බර ද්වි පාර්ශවීය ගැලපීමේ ගැටලුවක් ලෙස මම සලකමි . වෙනත් වචන වලින් කිවහොත්, නෝඩ් කට්ටල දෙකක් ඇත: මුල් පික්සෙල් සහ පලත් පික්සල්. කට්ටල දෙක හරහා එක් එක් පික්සෙල් අතර දාරයක් සාදනු ලැබේ (නමුත් කට්ටලයක් තුළ දාර නිර්මාණය නොවේ). දාරයක පිරිවැය හෝ බර යනු ඉහත විස්තර කර ඇති පරිදි පික්සල් දෙක අතර යුක්ලිඩියානු දුර වේ. සමීප වර්ණ දෙක දෘශ්‍යමය වේ, පික්සෙල් අතර පිරිවැය අඩු වේ.

ද්වි පාර්ශවීය ගැලපුම් උදාහරණය

මෙය N 2 ප්‍රමාණයේ පිරිවැය අනුකෘතියක් නිර්මාණය කරයි . N = 123520 ඇති මෙම රූප සඳහා, පිරිවැය පූර්ණ සංඛ්‍යා ලෙස නිරූපණය කිරීම සඳහා දළ වශයෙන් 40 GB මතකයක් අවශ්‍ය වන අතර අඩක් කෙටි සංඛ්‍යා ලෙස දැක්විය යුතුය. කෙසේ හෝ උත්සාහයක් දැරීමට තරම් ප්‍රමාණවත් මතකයක් මගේ යන්ත්‍රයේ නොතිබුණි. තවත් ගැටළුවක් වන්නේ මෙම ගැටළුව විසඳීම සඳහා භාවිතා කළ හැකි හංගේරියානු ඇල්ගොරිතම නොහොත් ජොන්කර්-වොල්ජන්ට් ඇල්ගොරිතම N 3 වේලාව තුළ ක්‍රියාත්මක වීමයි. නිශ්චිතවම ගණනය කළ හැකි වුවත්, එක් රූපයකට විසඳුමක් ජනනය කිරීමට පැය හෝ දින ගතවනු ඇත.

මෙම ගැටළුව මඟහරවා ගැනීම සඳහා, මම අහඹු ලෙස පික්සෙල් ලැයිස්තු දෙකම වර්ග කර, ලැයිස්තු සී කැබලිවලට බෙදමි, එක් එක් උප ලැයිස්තු යුගල මත ජොන්කර්-වොල්ජන්ට් ඇල්ගොරිතම C ++ ක්‍රියාත්මක කර, පසුව අවසන් සිතියම් නිර්මාණය කිරීම සඳහා නැවත ලැයිස්තු වලට සම්බන්ධ වෙමි. එමනිසා, පහත කේතය මඟින් කෙනෙකුට සැබවින්ම ප්‍රශස්ත විසඳුමක් සොයා ගැනීමට ඉඩ සලසයි. එමඟින් කුට්ටි ප්‍රමාණය C 1 ට සැකසීමට (ප්‍රමාණවත් කැබැල්ලක් නැත) සහ ප්‍රමාණවත් මතකයක් ඇත. මෙම රූප සඳහා, මම C 16 ලෙස සකසා ඇති අතර එමඟින් N 7720 බවට පත් වේ, එක් රූපයකට මිනිත්තු කිහිපයක් ගතවේ.

මෙය ක්‍රියාත්මක වන්නේ ඇයිදැයි සිතා බැලීමට සරල ක්‍රමයක් නම් අහඹු ලෙස පික්සෙල් ලැයිස්තුව වර්ග කර උප කුලකයක් ගැනීම රූපය නියැදි කිරීම හා සමානයි. එබැවින් C = 16 සැකසීමෙන්, එය හරියට N / C ප්‍රමාණයේ අහඹු සාම්පල 16 ක් මුල් හා පලත් වලින් ලබා ගැනීම හා සමානයි. ලැයිස්තු බෙදීමට වඩා හොඳ ක්‍රම ඇති බව පිළිගත යුතුය, නමුත් අහඹු ප්‍රවේශයක් යහපත් ප්‍රති .ල ලබා දෙයි.

import subprocess
import multiprocessing as mp
import sys
import os
import sge
from random import shuffle
from PIL import Image
import numpy as np
import LAPJV
import pdb

def getError(p1, p2):
    return (p1[0]-p2[0])**2 + (p1[1]-p2[1])**2 + (p1[2]-p2[2])**2

def getCostMatrix(pallete_list, source_list):
    num_pixels = len(pallete_list)
    matrix = np.zeros((num_pixels, num_pixels))

    for i in range(num_pixels):
        for j in range(num_pixels):
            matrix[i][j] = getError(pallete_list[i], source_list[j])

    return matrix

def chunks(l, n):
    if n < 1:
        n = 1
    return [l[i:i + n] for i in range(0, len(l), n)]

def imageToColorList(img_file):
    i = Image.open(img_file)

    pixels = i.load()
    width, height = i.size

    all_pixels = []
    for x in range(width):
        for y in range(height):
            pixel = pixels[x, y]
            all_pixels.append(pixel)

    return all_pixels

def colorListToImage(color_list, old_img_file, new_img_file, mapping):
    i = Image.open(old_img_file)

    pixels = i.load()
    width, height = i.size
    idx = 0

    for x in range(width):
        for y in range(height):
            pixels[x, y] = color_list[mapping[idx]]
            idx += 1

    i.save(new_img_file)

def getMapping(pallete_list, source_list):
    matrix = getCostMatrix(source_list, pallete_list)
    result = LAPJV.lap(matrix)[1]
    ret = []
    for i in range(len(pallete_list)):
        ret.append(result[i])
    return ret

def randomizeList(l):
    rdm_l = list(l)
    shuffle(rdm_l)
    return rdm_l

def getPartialMapping(zipped_chunk):
    pallete_chunk = zipped_chunk[0]
    source_chunk = zipped_chunk[1]
    subl_pallete = map(lambda v: v[1], pallete_chunk)
    subl_source = map(lambda v: v[1], source_chunk)
    mapping = getMapping(subl_pallete, subl_source)
    return mapping

def getMappingWithPartitions(pallete_list, source_list, C = 1):
    rdm_pallete = randomizeList(enumerate(pallete_list))
    rdm_source = randomizeList(enumerate(source_list))
    num_pixels = len(rdm_pallete)
    real_mapping = [0] * num_pixels

    chunk_size = int(num_pixels / C)

    chunked_rdm_pallete = chunks(rdm_pallete, chunk_size)
    chunked_rdm_source = chunks(rdm_source, chunk_size)
    zipped_chunks = zip(chunked_rdm_pallete, chunked_rdm_source)

    pool = mp.Pool(2)
    mappings = pool.map(getPartialMapping, zipped_chunks)

    for mapping, zipped_chunk in zip(mappings, zipped_chunks):
        pallete_chunk = zipped_chunk[0]
        source_chunk = zipped_chunk[1]
        for idx1,idx2 in enumerate(mapping):
            src_px = source_chunk[idx1]
            pal_px = pallete_chunk[idx2]
            real_mapping[src_px[0]] = pal_px[0]

    return real_mapping

def run(pallete_name, source_name, output_name):
    print("Getting Colors...")
    pallete_list = imageToColorList(pallete_name)
    source_list = imageToColorList(source_name)

    print("Creating Mapping...")
    mapping = getMappingWithPartitions(pallete_list, source_list, C = 16)

    print("Generating Image...");
    colorListToImage(pallete_list, source_name, output_name, mapping)

if __name__ == '__main__':
    pallete_name = sys.argv[1]
    source_name = sys.argv[2]
    output_name = sys.argv[3]
    run(pallete_name, source_name, output_name)

ප්රතිපල:

ඇඩිට්සුගේ විසඳුම මෙන්, මෙම රූප සියල්ලම එකම පරාමිතීන් භාවිතා කරමින් ජනනය කරන ලද්දකි. මෙහි ඇති එකම පරාමිතිය C වන අතර එය හැකි තරම් අඩු ලෙස සැකසිය යුතුය. මට නම්, සී = 16 වේගය සහ ගුණාත්මකභාවය අතර හොඳ සමබරතාවයක් විය.

සියලුම පින්තූර: http://imgur.com/a/RCZiX#0

ඇමරිකානු ගොතික් පලත්

මොනා-ගොතික් කෑගැසීම-ගොතික්

මොනා ලීසා පලත්

ගොතික්-මොනා කෑගැසීම-මොනා

තරු රාත්‍රී පලත්

මොනා-රාත්‍රිය ගංගා රාත්‍රිය

කෑගැසීමේ පලත්

ගොතික්-කෑගැසීම මොනා-කෑගැසීම

ගංගා තලය

ගොතික්-ගෝල මොනා-ගෝල

ගෝලාකාර පලත්

ගොතික්-ගෝල මොනා-ගෝල


4
මම ඇත්තටම කැමතියි (කෑගැසීම -> තරු රාත්‍රිය) සහ (ගෝලාකාර -> තරු රාත්‍රිය). (ගෝලාකාර -> මොනා ලිසා) ද එතරම් නරක නැත, නමුත් මම තව දුරටත් වියැකී යනු දැකීමට කැමැත්තෙමි.
ජෝන් ඩ්වොරක්

ලොල්, මම ද්වි පාර්ශවීය ප්‍රස්ථාර ගැලපීම ගැන එකම දේ සිතමින් සිටියෙමි, නමුත් එම අදහස අතහැර දැමුවේ N ^ 3 නිසාය.
RobAu

මෙම "පාහේ-නිර්ණායක" ඇල්ගොරිතම IMO හි සියලු නිර්ණායකයන්ට පහර දෙන අතර හොඳ අහඹු ලෙස ඒවා සමඟ නැගී සිටියි. මම එයට කැමතියි.
හොබ්ස්

1
ප්‍රශස්ත විසඳුමක් පිළිබඳ ඔබේ අදහස සමඟ මම එකඟ නොවෙමි. මන්ද? වියළීම මඟින් ප්‍රත්‍යක්‍ෂම ගුණාත්මකභාවය (මිනිසුන් සඳහා) වැඩි දියුණු කළ හැකි නමුත් ඔබේ අර්ථ දැක්වීම භාවිතා කර අඩු ලකුණු ප්‍රමාණයක් ලබා ගත හැකිය. CIELUV වැනි දෙයක් හරහා RGB භාවිතා කිරීම වැරැද්දකි.
තෝමස් එඩිං

40

සී # වින්ෆෝම් - විෂුවල් ස්ටුඩියෝ 2010

සංස්කරණය ඩිතරින් එකතු කරන ලදි.

එය මගේ අහඹු-හුවමාරු ඇල්ගොරිතමයේ අනුවාදයයි - හොබ්ස් රසය. මට තවමත් දැනෙන්නේ යම් ආකාරයක අහඹු නොවන වියළීමකට වඩා හොඳ දෙයක් කළ හැකි බවයි ...

Y-Cb-Cr අවකාශයේ වර්ණ විස්තාරණය (jpeg සම්පීඩනයේදී මෙන්)

අදියර දෙකක විස්තාරණය:

  1. දීප්තියේ අනුපිළිවෙලින් ප්‍රභවයෙන් පික්සෙල් පිටපත. මෙය දැනටමත් හොඳ ප්‍රතිරූපයක් ලබා දෙයි, නමුත් අවිනිශ්චිත - පාහේ අළු පරිමාණය - ආසන්න වශයෙන් 0 වේලාව තුළ
  2. අහඹු ලෙස පික්සෙල් හුවමාරුව. මෙය පික්සෙල් අඩංගු 3x3 සෛල තුළ වඩා හොඳ ඩෙල්ටාවක් (ප්‍රභවයට සාපේක්ෂව) ලබා දෙන්නේ නම් හුවමාරුව සිදු කෙරේ. එබැවින් එය වියැකී යාමේ බලපෑමකි. ඩෙල්ටාව ගණනය කරනු ලබන්නේ විවිධ සංරචකවල බරක් නොමැතිව Y-Cr-Cb අවකාශය මත ය.

මෙය අහඹු ලෙස පළමු අහඹු හුවමාරුවකින් තොරව ob හොබ්ස් විසින් භාවිතා කරන එකම ක්‍රමයයි. මගේ කාලය කෙටි වේ (භාෂා ගණන?) සහ මම සිතන්නේ මගේ රූප වඩා හොඳය (බොහෝ විට භාවිතා කරන වර්ණ අවකාශය වඩාත් නිවැරදි විය හැකිය).

වැඩසටහන් භාවිතය: ඔබේ c: \ temp ෆෝල්ඩරයේ .png පින්තූර දමන්න, පලත් රූපය තෝරා ගැනීම සඳහා ලැයිස්තුවේ මූලද්‍රව්‍යය පරීක්ෂා කරන්න, ප්‍රභව රූපය තෝරා ගැනීමට ලැයිස්තුවේ මූලද්‍රව්‍යය තෝරන්න (එතරම් පරිශීලක හිතකාමී නොවේ). විස්තාරණය ආරම්භ කිරීම සඳහා ආරම්භක බොත්තම ක්ලික් කරන්න, සුරැකීම ස්වයංක්‍රීය වේ (ඔබ අකමැති වුවද - පරෙස්සම් වන්න).

තත්පර 90 ට අඩු විස්තාරණ කාලය.

යාවත්කාලීන කළ ප්‍රති .ල

පලෙට්: ඇමරිකානු ගොතික්

මොනා ලීසා දේදුන්න ගඟ කෑගැසීම තරු රාත්‍රිය

පලෙට්: මොනා ලීසා

ඇමරිකානු ගොතික් දේදුන්න ගඟ කෑගැසීම තරු රාත්‍රිය

පලත්: දේදුන්න

ඇමරිකානු ගොතික් මොනා ලීසා ගඟ කෑගැසීම තරු රාත්‍රිය

පලෙට්: ගඟ

ඇමරිකානු ගොතික් මොනා ලීසා දේදුන්න කෑගැසීම තරු රාත්‍රිය

පලත්: කෑගැසීම

ඇමරිකානු ගොතික් මොනා ලීසා දේදුන්න ගඟ තරු රාත්‍රිය

පලත්: තරු රාත්‍රිය

ඇමරිකානු ගොතික් මොනා ලීසා දේදුන්න ගඟ කෑගැසීම

Form1.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Imaging;
using System.IO;

namespace Palette
{
    public struct YRB
    {
        public int y, cb, cr;

        public YRB(int r, int g, int b)
        {
            y = (int)(0.299 * r + 0.587 * g + 0.114 * b);
            cb = (int)(128 - 0.168736 * r - 0.331264 * g + 0.5 * b);
            cr = (int)(128 + 0.5 * r - 0.418688 * g - 0.081312 * b);
        }
    }

    public struct Pixel
    {
        private const int ARGBAlphaShift = 24;
        private const int ARGBRedShift = 16;
        private const int ARGBGreenShift = 8;
        private const int ARGBBlueShift = 0;

        public int px, py;
        private uint _color;
        public YRB yrb;

        public Pixel(uint col, int px = 0, int py = 0)
        {
            this.px = px;
            this.py = py;
            this._color = col;
            yrb = new YRB((int)(col >> ARGBRedShift) & 255, (int)(col >> ARGBGreenShift) & 255, (int)(col >> ARGBBlueShift) & 255); 
        }

        public uint color
        {
            get { 
                return _color; 
            }
            set {
                _color = color;
                yrb = new YRB((int)(color >> ARGBRedShift) & 255, (int)(color >> ARGBGreenShift) & 255, (int)(color >> ARGBBlueShift) & 255);
            }
        }

        public int y
        {
            get { return yrb.y; }
        }
        public int cr
        {
            get { return yrb.cr; }
        }
        public int cb
        {
            get { return yrb.cb; }
        }
    }

    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            DirectoryInfo di = new System.IO.DirectoryInfo(@"c:\temp\");
            foreach (FileInfo file in di.GetFiles("*.png"))
            {
                ListViewItem item = new ListViewItem(file.Name);
                item.SubItems.Add(file.FullName);
                lvFiles.Items.Add(item);
            }
        }

        private void lvFiles_ItemSelectionChanged(object sender, ListViewItemSelectionChangedEventArgs e)
        {
            if (e.IsSelected)
            {
                string file = e.Item.SubItems[1].Text;
                GetImagePB(pbSource, file);
                pbSource.Tag = file; 
                DupImage(pbSource, pbOutput);

                this.Width = pbOutput.Width + pbOutput.Left + 20;
                this.Height = Math.Max(pbOutput.Height, pbPalette.Height)+lvFiles.Height*2;   
            }
        }

        private void lvFiles_ItemCheck(object sender, ItemCheckEventArgs e)
        {
            foreach (ListViewItem item in lvFiles.CheckedItems)
            {
                if (item.Index != e.Index) item.Checked = false;
            }
            string file = lvFiles.Items[e.Index].SubItems[1].Text;
            GetImagePB(pbPalette, file);
            pbPalette.Tag = lvFiles.Items[e.Index].SubItems[0].Text; 

            this.Width = pbOutput.Width + pbOutput.Left + 20;
            this.Height = Math.Max(pbOutput.Height, pbPalette.Height) + lvFiles.Height * 2;   
        }

        Pixel[] Palette;
        Pixel[] Source;

        private void BtnStart_Click(object sender, EventArgs e)
        {
            lvFiles.Enabled = false;
            btnStart.Visible = false;
            progressBar.Visible = true; 
            DupImage(pbSource, pbOutput);

            Work(pbSource.Image as Bitmap, pbPalette.Image as Bitmap, pbOutput.Image as Bitmap);

            string newfile = (string)pbSource.Tag +"-"+ (string)pbPalette.Tag;
            pbOutput.Image.Save(newfile, ImageFormat.Png);   

            lvFiles.Enabled = true;
            btnStart.Visible = true;
            progressBar.Visible = false;
        }

        private void Work(Bitmap srcb, Bitmap palb, Bitmap outb)
        {
            GetData(srcb, out Source);
            GetData(palb, out Palette);

            FastBitmap fout = new FastBitmap(outb);
            FastBitmap fsrc = new FastBitmap(srcb);
            int pm = Source.Length;
            int w = outb.Width;
            int h = outb.Height;
            progressBar.Maximum = pm;

            fout.LockImage();
            for (int p = 0; p < pm; p++)
            {
                fout.SetPixel(Source[p].px, Source[p].py, Palette[p].color);
            }
            fout.UnlockImage();

            pbOutput.Refresh();

            var rnd = new Random();
            int totsw = 0;
            progressBar.Maximum = 200;
            for (int i = 0; i < 200; i++)
            {
                int nsw = 0;
                progressBar.Value = i;
                fout.LockImage();
                fsrc.LockImage();
                for (int j = 0; j < 200000; j++)
                {
                    nsw += CheckSwap(fsrc, fout, 1 + rnd.Next(w - 2), 1 + rnd.Next(h - 2), 1 + rnd.Next(w - 2), 1 + rnd.Next(h - 2));
                }
                totsw += nsw;
                lnCurSwap.Text = nsw.ToString();
                lnTotSwap.Text = totsw.ToString();
                fout.UnlockImage();
                fsrc.UnlockImage();
                pbOutput.Refresh();
                Application.DoEvents();
                if (nsw == 0)
                {
                    break;
                }
            }            
        }

        int CheckSwap(FastBitmap fsrc, FastBitmap fout, int x1, int y1, int x2, int y2)
        {
            const int fmax = 3;
            YRB ov1 = new YRB();
            YRB sv1 = new YRB();
            YRB ov2 = new YRB();
            YRB sv2 = new YRB();

            int f;
            for (int dx = -1; dx <= 1; dx++)
            {
                for (int dy = -1; dy <= 1; dy++)
                {
                    f = (fmax - Math.Abs(dx) - Math.Abs(dy));
                    {
                        Pixel o1 = new Pixel(fout.GetPixel(x1 + dx, y1 + dy));
                        ov1.y += o1.y * f;
                        ov1.cb += o1.cr * f;
                        ov1.cr += o1.cb * f;

                        Pixel s1 = new Pixel(fsrc.GetPixel(x1 + dx, y1 + dy));
                        sv1.y += s1.y * f;
                        sv1.cb += s1.cr * f;
                        sv1.cr += s1.cb * f;

                        Pixel o2 = new Pixel(fout.GetPixel(x2 + dx, y2 + dy));
                        ov2.y += o2.y * f;
                        ov2.cb += o2.cr * f;
                        ov2.cr += o2.cb * f;

                        Pixel s2 = new Pixel(fsrc.GetPixel(x2 + dx, y2 + dy));
                        sv2.y += s2.y * f;
                        sv2.cb += s2.cr * f;
                        sv2.cr += s2.cb * f;
                    }
                }
            }
            YRB ox1 = ov1;
            YRB ox2 = ov2;
            Pixel oc1 = new Pixel(fout.GetPixel(x1, y1));
            Pixel oc2 = new Pixel(fout.GetPixel(x2, y2));
            ox1.y += fmax * oc2.y - fmax * oc1.y;
            ox1.cb += fmax * oc2.cr - fmax * oc1.cr;
            ox1.cr += fmax * oc2.cb - fmax * oc1.cb;
            ox2.y += fmax * oc1.y - fmax * oc2.y;
            ox2.cb += fmax  * oc1.cr - fmax * oc2.cr;
            ox2.cr += fmax * oc1.cb - fmax * oc2.cb;

            int curd = Delta(ov1, sv1, 1) + Delta(ov2, sv2, 1);
            int newd = Delta(ox1, sv1, 1) + Delta(ox2, sv2, 1);
            if (newd < curd)
            {
                fout.SetPixel(x1, y1, oc2.color);
                fout.SetPixel(x2, y2, oc1.color);
                return 1;
            }
            return 0;
        }

        int Delta(YRB p1, YRB p2, int sf)
        {
            int dy = (p1.y - p2.y);
            int dr = (p1.cr - p2.cr);
            int db = (p1.cb - p2.cb);

            return dy * dy * sf + dr * dr + db * db;
        }

        Bitmap GetData(Bitmap bmp, out Pixel[] Output)
        {
            FastBitmap fb = new FastBitmap(bmp);
            BitmapData bmpData = fb.LockImage(); 

            Output = new Pixel[bmp.Width * bmp.Height];

            int p = 0;
            for (int y = 0; y < bmp.Height; y++)
            {
                uint col = fb.GetPixel(0, y);
                Output[p++] = new Pixel(col, 0, y);

                for (int x = 1; x < bmp.Width; x++)
                {
                    col = fb.GetNextPixel();
                    Output[p++] = new Pixel(col, x, y);
                }
            }
            fb.UnlockImage(); // Unlock the bits.

            Array.Sort(Output, (a, b) => a.y - b.y);

            return bmp;
        }

        void DupImage(PictureBox s, PictureBox d)
        {
            if (d.Image != null)
                d.Image.Dispose();
            d.Image = new Bitmap(s.Image.Width, s.Image.Height);  
        }

        void GetImagePB(PictureBox pb, string file)
        {
            Bitmap bms = new Bitmap(file, false);
            Bitmap bmp = bms.Clone(new Rectangle(0, 0, bms.Width, bms.Height), PixelFormat.Format32bppArgb);
            bms.Dispose(); 
            if (pb.Image != null)
                pb.Image.Dispose();
            pb.Image = bmp;
        }
    }

    //Adapted from Visual C# Kicks - http://www.vcskicks.com/
    unsafe public class FastBitmap
    {
        private Bitmap workingBitmap = null;
        private int width = 0;
        private BitmapData bitmapData = null;
        private Byte* pBase = null;

        public FastBitmap(Bitmap inputBitmap)
        {
            workingBitmap = inputBitmap;
        }

        public BitmapData LockImage()
        {
            Rectangle bounds = new Rectangle(Point.Empty, workingBitmap.Size);

            width = (int)(bounds.Width * 4 + 3) & ~3;

            //Lock Image
            bitmapData = workingBitmap.LockBits(bounds, ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb);
            pBase = (Byte*)bitmapData.Scan0.ToPointer();
            return bitmapData;
        }

        private uint* pixelData = null;

        public uint GetPixel(int x, int y)
        {
            pixelData = (uint*)(pBase + y * width + x * 4);
            return *pixelData;
        }

        public uint GetNextPixel()
        {
            return *++pixelData;
        }

        public void GetPixelArray(int x, int y, uint[] Values, int offset, int count)
        {
            pixelData = (uint*)(pBase + y * width + x * 4);
            while (count-- > 0)
            {
                Values[offset++] = *pixelData++;
            }
        }

        public void SetPixel(int x, int y, uint color)
        {
            pixelData = (uint*)(pBase + y * width + x * 4);
            *pixelData = color;
        }

        public void SetNextPixel(uint color)
        {
            *++pixelData = color;
        }

        public void UnlockImage()
        {
            workingBitmap.UnlockBits(bitmapData);
            bitmapData = null;
            pBase = null;
        }
    }

}

Form1.Designer.cs

namespace Palette
{
    partial class Form1
    {
        /// <summary>
        /// Variabile di progettazione necessaria.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Liberare le risorse in uso.
        /// </summary>
        /// <param name="disposing">ha valore true se le risorse gestite devono essere eliminate, false in caso contrario.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Codice generato da Progettazione Windows Form

        /// <summary>
        /// Metodo necessario per il supporto della finestra di progettazione. Non modificare
        /// il contenuto del metodo con l'editor di codice.
        /// </summary>
        private void InitializeComponent()
        {
            this.components = new System.ComponentModel.Container();
            this.panel = new System.Windows.Forms.FlowLayoutPanel();
            this.pbSource = new System.Windows.Forms.PictureBox();
            this.pbPalette = new System.Windows.Forms.PictureBox();
            this.pbOutput = new System.Windows.Forms.PictureBox();
            this.btnStart = new System.Windows.Forms.Button();
            this.progressBar = new System.Windows.Forms.ProgressBar();
            this.imageList1 = new System.Windows.Forms.ImageList(this.components);
            this.lvFiles = new System.Windows.Forms.ListView();
            this.lnTotSwap = new System.Windows.Forms.Label();
            this.lnCurSwap = new System.Windows.Forms.Label();
            this.panel.SuspendLayout();
            ((System.ComponentModel.ISupportInitialize)(this.pbSource)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.pbPalette)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.pbOutput)).BeginInit();
            this.SuspendLayout();
            // 
            // panel
            // 
            this.panel.AutoScroll = true;
            this.panel.AutoSize = true;
            this.panel.Controls.Add(this.pbSource);
            this.panel.Controls.Add(this.pbPalette);
            this.panel.Controls.Add(this.pbOutput);
            this.panel.Dock = System.Windows.Forms.DockStyle.Top;
            this.panel.Location = new System.Drawing.Point(0, 0);
            this.panel.Name = "panel";
            this.panel.Size = new System.Drawing.Size(748, 266);
            this.panel.TabIndex = 3;
            this.panel.WrapContents = false;
            // 
            // pbSource
            // 
            this.pbSource.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
            this.pbSource.Location = new System.Drawing.Point(3, 3);
            this.pbSource.Name = "pbSource";
            this.pbSource.Size = new System.Drawing.Size(157, 260);
            this.pbSource.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize;
            this.pbSource.TabIndex = 1;
            this.pbSource.TabStop = false;
            // 
            // pbPalette
            // 
            this.pbPalette.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
            this.pbPalette.Location = new System.Drawing.Point(166, 3);
            this.pbPalette.Name = "pbPalette";
            this.pbPalette.Size = new System.Drawing.Size(172, 260);
            this.pbPalette.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize;
            this.pbPalette.TabIndex = 3;
            this.pbPalette.TabStop = false;
            // 
            // pbOutput
            // 
            this.pbOutput.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
            this.pbOutput.Location = new System.Drawing.Point(344, 3);
            this.pbOutput.Name = "pbOutput";
            this.pbOutput.Size = new System.Drawing.Size(172, 260);
            this.pbOutput.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize;
            this.pbOutput.TabIndex = 4;
            this.pbOutput.TabStop = false;
            // 
            // btnStart
            // 
            this.btnStart.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
            this.btnStart.Location = new System.Drawing.Point(669, 417);
            this.btnStart.Name = "btnStart";
            this.btnStart.Size = new System.Drawing.Size(79, 42);
            this.btnStart.TabIndex = 4;
            this.btnStart.Text = "Start";
            this.btnStart.UseVisualStyleBackColor = true;
            this.btnStart.Click += new System.EventHandler(this.BtnStart_Click);
            // 
            // progressBar
            // 
            this.progressBar.Dock = System.Windows.Forms.DockStyle.Bottom;
            this.progressBar.Location = new System.Drawing.Point(0, 465);
            this.progressBar.Name = "progressBar";
            this.progressBar.Size = new System.Drawing.Size(748, 16);
            this.progressBar.TabIndex = 5;
            // 
            // imageList1
            // 
            this.imageList1.ColorDepth = System.Windows.Forms.ColorDepth.Depth8Bit;
            this.imageList1.ImageSize = new System.Drawing.Size(16, 16);
            this.imageList1.TransparentColor = System.Drawing.Color.Transparent;
            // 
            // lvFiles
            // 
            this.lvFiles.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left) 
            | System.Windows.Forms.AnchorStyles.Right)));
            this.lvFiles.CheckBoxes = true;
            this.lvFiles.HideSelection = false;
            this.lvFiles.Location = new System.Drawing.Point(12, 362);
            this.lvFiles.MultiSelect = false;
            this.lvFiles.Name = "lvFiles";
            this.lvFiles.Size = new System.Drawing.Size(651, 97);
            this.lvFiles.Sorting = System.Windows.Forms.SortOrder.Ascending;
            this.lvFiles.TabIndex = 7;
            this.lvFiles.UseCompatibleStateImageBehavior = false;
            this.lvFiles.View = System.Windows.Forms.View.List;
            this.lvFiles.ItemCheck += new System.Windows.Forms.ItemCheckEventHandler(this.lvFiles_ItemCheck);
            this.lvFiles.ItemSelectionChanged += new System.Windows.Forms.ListViewItemSelectionChangedEventHandler(this.lvFiles_ItemSelectionChanged);
            // 
            // lnTotSwap
            // 
            this.lnTotSwap.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
            this.lnTotSwap.Location = new System.Drawing.Point(669, 362);
            this.lnTotSwap.Name = "lnTotSwap";
            this.lnTotSwap.Size = new System.Drawing.Size(58, 14);
            this.lnTotSwap.TabIndex = 8;
            this.lnTotSwap.Text = "label1";
            // 
            // lnCurSwap
            // 
            this.lnCurSwap.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
            this.lnCurSwap.Location = new System.Drawing.Point(669, 385);
            this.lnCurSwap.Name = "lnCurSwap";
            this.lnCurSwap.Size = new System.Drawing.Size(58, 14);
            this.lnCurSwap.TabIndex = 9;
            this.lnCurSwap.Text = "label1";
            // 
            // Form1
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.BackColor = System.Drawing.SystemColors.ControlDark;
            this.ClientSize = new System.Drawing.Size(748, 481);
            this.Controls.Add(this.lnCurSwap);
            this.Controls.Add(this.lnTotSwap);
            this.Controls.Add(this.lvFiles);
            this.Controls.Add(this.progressBar);
            this.Controls.Add(this.btnStart);
            this.Controls.Add(this.panel);
            this.Name = "Form1";
            this.Text = "Form1";
            this.Load += new System.EventHandler(this.Form1_Load);
            this.panel.ResumeLayout(false);
            this.panel.PerformLayout();
            ((System.ComponentModel.ISupportInitialize)(this.pbSource)).EndInit();
            ((System.ComponentModel.ISupportInitialize)(this.pbPalette)).EndInit();
            ((System.ComponentModel.ISupportInitialize)(this.pbOutput)).EndInit();
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.FlowLayoutPanel panel;
        private System.Windows.Forms.PictureBox pbSource;
        private System.Windows.Forms.PictureBox pbPalette;
        private System.Windows.Forms.PictureBox pbOutput;
        private System.Windows.Forms.Button btnStart;
        private System.Windows.Forms.ProgressBar progressBar;
        private System.Windows.Forms.ImageList imageList1;
        private System.Windows.Forms.ListView lvFiles;
        private System.Windows.Forms.Label lnTotSwap;
        private System.Windows.Forms.Label lnCurSwap;
    }
}

Program.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;

namespace Palette
{
    static class Program
    {
        /// <summary>
        /// Punto di ingresso principale dell'applicazione.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }
    }
}

සම්පාදනය කිරීම සඳහා ව්‍යාපෘති දේපලවල 'අනාරක්ෂිත කේතය' පරීක්ෂා කරන්න.


5
IMO මෙය හොඳම
ප්‍රති results ල

10
එය භයානක දේදුන්න තාලයක් සමඟ ඇත්තෙන්ම ඇදහිය නොහැකි ය.
මයිකල් බී

2
පුදුමයි, ජයග්රාහකයා!
jjrv

39

පයිතන්

සංස්කරණය කරන්න: ප්‍රති results ල වඩාත් හොඳින් අර්ථ දැක්වීමට ඔබට ඇත්ත වශයෙන්ම ImageFilter සමඟ ප්‍රභවය මුවහත් කළ හැකි බව අවබෝධ විය.

දේදුන්න -> මොනා ලීසා (මුවහත් කළ මොනා ලිසා ප්‍රභවය, දීප්තිය පමණි)

රූප විස්තරය මෙහි ඇතුළත් කරන්න

දේදුන්න -> මොනා ලීසා (මුවහත් නොකළ ප්‍රභවය, බර Y = 10, I = 10, Q = 0)

රූප විස්තරය මෙහි ඇතුළත් කරන්න

මොනා ලිසා -> ඇමරිකානු ගොතික් (මුවහත් නොකළ ප්‍රභවය, දීප්තිය පමණි)

රූප විස්තරය මෙහි ඇතුළත් කරන්න

මොනා ලිසා -> ඇමරිකානු ගොතික් (මුවහත් නොකළ ප්‍රභවය, බර Y = 1, I = 10, Q = 1)

රූප විස්තරය මෙහි ඇතුළත් කරන්න

ගංගාව -> දේදුන්න (මුවහත් නොකළ ප්‍රභවය, දීප්තිය පමණි)

රූප විස්තරය මෙහි ඇතුළත් කරන්න

මූලික වශයෙන්, එය පින්තූර දෙකෙන් සියලුම පික්සෙල් ලැයිස්තු දෙකකට ලබා ගනී.

යතුර ලෙස දීප්තියෙන් ඒවා වර්ග කරන්න. YIQ හි Y දීප්තිය නිරූපණය කරයි.

එවිට, ප්‍රභවයේ ඇති සෑම පික්සෙල් සඳහාම (එය දීප්තියේ අනුපිළිවෙලින්) RGB අගය එකම දර්ශකයේ පික්සෙල් වලින් ලබා ගන්න.

import Image, ImageFilter, colorsys

def getPixels(image):
    width, height = image.size
    pixels = []
    for x in range(width):
        for y in range(height):
            pixels.append([(x,y), image.getpixel((x,y))])
    return pixels

def yiq(pixel):
    # y is the luminance
    y,i,q = colorsys.rgb_to_yiq(pixel[1][0], pixel[1][6], pixel[1][7])
    # Change the weights accordingly to get different results
    return 10*y + 0*i + 0*q

# Open the images
source  = Image.open('ml.jpg')
pallete = Image.open('rainbow.png')

# Sharpen the source... It won't affect the palette anyway =D
source = source.filter(ImageFilter.SHARPEN)

# Sort the two lists by luminance
sourcePixels  = sorted(getPixels(source),  key=yiq)
palletePixels = sorted(getPixels(pallete), key=yiq)

copy = Image.new('RGB', source.size)

# Iterate through all the coordinates of source
# And set the new color
index = 0
for sourcePixel in sourcePixels:
    copy.putpixel(sourcePixel[0], palletePixels[index][8])
    index += 1

# Save the result
copy.save('copy.png')

සජීවිකරණවල ප්‍රවණතාව පවත්වා ගැනීමට ...

කෑගැසීමේ පික්සෙල් තරු රාත්‍රියට ඉක්මන් කර ඇති අතර අනෙක් අතට

රූප විස්තරය මෙහි ඇතුළත් කරන්න රූප විස්තරය මෙහි ඇතුළත් කරන්න


2
එම සරල අදහස ඇත්තෙන්ම හොඳින් ක්‍රියාත්මක වේ. එය දිගු කර බරින් යුත් දීප්තිය, සන්තෘප්තිය සහ පැහැය භාවිතා කළ හැකිදැයි මම කල්පනා කරමි. (උදා: 10 * L + S + H) එකම ප්‍රදේශ වර්ණ ගැලපීම ලබා ගැනීම සඳහා.
මූගී

1
imagesbitpwnr ඔබේ පින්තූර මගේ ස්ක්‍රිප්ට් පසුකර නොයන නමුත් එය නිසැකවම පාහේ ඔබ මුලින් මා සතුව ඇති තරමක් වෙනස් jpegs භාවිතා කරන නිසා විශාල ගනුදෙනුවක් නැත. කෙසේ වෙතත් මට ඔබගේ කේතය ධාවනය කිරීමට හැකි වූයේ [6], [7] සහ [8] [1], [2] සහ [1] සමඟ ප්‍රතිස්ථාපනය කිරීමෙන් පසුව පමණි. මට එකම පින්තූර ලැබෙමින් පවතින නමුත් එය ඉතා අද්විතීය අකුරු ය: පී
කැල්වින්ගේ විනෝදාංශ

1
ඔබේ පින්තූර ඉතා පැහැදිලිය, නමුත් තරමක්
අවුල් සහගත ය

@ කැල්වින්ස් හොබීස් ඕප්ස්, යතුරු ලියනය නිවැරදි කළේය.
දෛශිකකරණය

@bitpwner මගේ සජීවිකරණ ස්ක්‍රිප්ට් ප්‍රදර්ශනය කිරීම සඳහා යූ ටියුබ් වීඩියෝවක් තුළ ඔබගේ පින්තූර කිහිපයක් භාවිතා කළහොත් එය හරිද?
කැල්වින්ගේ විනෝදාංශ

25

ජේ

පින්තූර url දෙකක් මත ධාවනය කරන්න.

JS පැකේජයක් ලෙස ඔබට එය බ්‍රව්සරයේ තනිවම ක්‍රියාත්මක කළ හැකිය. විවිධ සැකසුම් සමඟ සෙල්ලම් කරන ෆිද්ල්ස් සපයනු ලැබේ. කරුණාකර මතක තබා ගන්න මෙම ප්‍රහේලිකාව: http://jsfiddle.net/eithe/J7jEk/ සෑම විටම යාවත්කාලීනව පවතී (සියලු සැකසුම් අඩංගු වේ). මෙය වර්ධනය වන බැවින් (නව විකල්ප එකතු කරනු ලැබේ), මම පෙර පැවති සියලු ප්‍රබන්ධ යාවත්කාලීන නොකරමි.

ඇමතුම්

  • f("string to image (palette)", "string to image", {object of options});
  • f([[palette pixel], [palette pixel], ..., "string to image", {object of options});

විකල්ප

  • ඇල්ගොරිතමය: 'balanced', 'surrounding', 'reverse', 'hsv', 'yiq','lab'
  • වේගය: සජීවිකරණ වේගය
  • චලනය: true- සජීවිකරණය ආරම්භයේ සිට අවසානය දක්වා චලනය පෙන්විය යුතුද?
  • අවට: 'surrounding'ඇල්ගොරිතම තෝරාගනු ලැබුවහොත් මෙය ලබා දී ඇති පික්සෙල් බර ගණනය කිරීමේදී සැලකිල්ලට ගනු ලබන අවට බරයි
  • hsv: 'hsv'ඇල්ගොරිතම තෝරාගනු ලැබුවහොත් මෙම පරාමිතීන් බරට කෙතරම් වර්ණ, සන්තෘප්තිය සහ වටිනාකම බලපායිද යන්න පාලනය කරයි
  • yiq: 'qiv'ඇල්ගොරිතම තෝරාගෙන තිබේ නම් මෙම පරාමිතීන් බරට yiq බලපාන ආකාරය පාලනය කරයි
  • විද්‍යාගාරය: 'lab'ඇල්ගොරිතම තෝරාගනු ලැබුවහොත් මෙම පරාමිතීන් බර කිරිමට කොතරම් බලපෑමක් කරනවාද යන්න පාලනය කරයි
  • ශබ්දය: බරට අහඹු ලෙස කොපමණ ප්‍රමාණයක් එකතු වේ ද?
  • අද්විතීය: පලතේ සිට පික්සෙල් භාවිතා කළ යුත්තේ එක් වරක් පමණි (බලන්න: ෆොටෝමොසයික්ස් හෝ: විදුලි බුබුලක් ප්‍රතිස්ථාපනය කිරීමට ක්‍රමලේඛකයින් කීයක් ගතවේද? )
  • pixel_1 / pixel_2 {පළල, උස}: පික්සෙල් ප්‍රමාණය (පික්සල් වලින්: D)

ගැලරිය (ප්‍රදර්ශන කුටි සඳහා මම සැමවිටම භාවිතා කරන්නේ මොනා ලිසා සහ ඇමරිකානු ගොතික්, වෙනත් නිශ්චිතව දක්වා නොමැති නම්):


සජීවිකරණය විශිෂ්ටයි! නමුත් ඔබේ රූපය සාමාන්‍යයට වඩා එක් පික්සෙල් කෙටි වේ.
කැල්වින්ගේ විනෝදාංශ

@ කැල්වින්ගේ විනෝදාංශ - එය තීන්තවලින් කපා ගත යුතුව තිබුණි: P බොහෝ විට වෙනස එන්නේ එතැනිනි. යාවත්කාලීන කරන ලදි!
eithed

මම මේකට කැමතියි: jsfiddle.net/q865W/4
ජස්ටින්

@ ක්වින්කන්ක්ස් චියර්ස්! බර තැබූ අනුවාදය සමග එය ඊටත් වඩා හොඳින් ක්රියා කරයි
eithed

වොව්. 0_0 එය ඇත්තෙන්ම හොඳයි. jsfiddle.net/q865W/6
ජස්ටින්

24

සී, විද්‍යාගාර වර්ණ අවකාශය සහ වැඩිදියුණු කළ වියළීම සමඟ

මම කිව්වේ මම ඉවරයි කියලා? මම බොරු කිව්වා. මම හිතන්නේ මගේ අනෙක් විසඳුමේ ඇති ඇල්ගොරිතම එහි ඇති හොඳම ඒවාය, නමුත් පර්ල් සංඛ්‍යා බිඳීමේ කාර්යයන් සඳහා ප්‍රමාණවත් නොවේ, එබැවින් මම සී හි මගේ වැඩ කටයුතු නැවත ක්‍රියාත්මක කළෙමි. එය දැන් මෙම ලිපියේ ඇති සියලුම පින්තූර ඉහළ ගුණාත්මකභාවයකින් ධාවනය කරයි මුල් පිටපතට වඩා මිනිත්තු 3 ක් පමණ වන අතර තරමක් අඩු ගුණාත්මක භාවය (0.5% මට්ටම) තත්පරයකට තත්පර 20-30 කින් ධාවනය වේ. මූලික වශයෙන් සියලුම වැඩ කටයුතු ඉමේජ් මැජික් සමඟ සිදු කෙරෙන අතර, වියළීම සිදු කරනු ලබන්නේ ඉමේජ් මැජික්ගේ cub නක ස්ප්ලයින් අන්තර් මැදිහත්වීමෙනි, එය වඩා හොඳ / අඩු රටා ප්‍රති .ලයක් ලබා දෙයි.

කේතය

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <unistd.h>
#include <wand/MagickWand.h>

#define ThrowWandException(wand) \
{ \
  char \
  *description; \
  \
  ExceptionType \
  severity; \
  \
  description=MagickGetException(wand,&severity); \
  (void) fprintf(stderr,"%s %s %lu %s\n",GetMagickModule(),description); \
  description=(char *) MagickRelinquishMemory(description); \
  abort(); \
  exit(-1); \
}

int width, height; /* Target image size */
MagickWand *source_wand, *target_wand, *img_wand, *target_lab_wand, *img_lab_wand;
PixelPacket *source_pixels, *target_pixels, *img_pixels, *target_lab_pixels, *img_lab_pixels;
Image *img, *img_lab, *target, *target_lab;
CacheView *img_lab_view, *target_lab_view;
ExceptionInfo *e;

MagickWand *load_image(const char *filename) {
  MagickWand *img = NewMagickWand();
  if (!MagickReadImage(img, filename)) {
    ThrowWandException(img);
  }
  return img;
}

PixelPacket *get_pixels(MagickWand *wand) {
  PixelPacket *ret = GetAuthenticPixels(
      GetImageFromMagickWand(wand), 0, 0,
      MagickGetImageWidth(wand), MagickGetImageHeight(wand), e);
  CatchException(e);
  return ret;
}

void sync_pixels(MagickWand *wand) {
  SyncAuthenticPixels(GetImageFromMagickWand(wand), e);
  CatchException(e);
}

MagickWand *transfer_pixels() {
  if (MagickGetImageWidth(source_wand) * MagickGetImageHeight(source_wand)
      != MagickGetImageWidth(target_wand) * MagickGetImageHeight(target_wand)) {
    perror("size mismtch");
  }

  MagickWand *img_wand = CloneMagickWand(target_wand);
  img_pixels = get_pixels(img_wand);
  memcpy(img_pixels, source_pixels, 
      MagickGetImageWidth(img_wand) * MagickGetImageHeight(img_wand) * sizeof(PixelPacket));

  sync_pixels(img_wand);
  return img_wand;
}

MagickWand *image_to_lab(MagickWand *img) {
  MagickWand *lab = CloneMagickWand(img);
  TransformImageColorspace(GetImageFromMagickWand(lab), LabColorspace);
  return lab;
}

int lab_distance(PixelPacket *a, PixelPacket *b) {
  int l_diff = (GetPixelL(a) - GetPixelL(b)) / 256,
      a_diff = (GetPixela(a) - GetPixela(b)) / 256,
      b_diff = (GetPixelb(a) - GetPixelb(b)) / 256;

  return (l_diff * l_diff + a_diff * a_diff + b_diff * b_diff);
}

int should_swap(int x1, int x2, int y1, int y2) {
  int dist = lab_distance(&img_lab_pixels[width * y1 + x1], &target_lab_pixels[width * y1 + x1])
           + lab_distance(&img_lab_pixels[width * y2 + x2], &target_lab_pixels[width * y2 + x2]);
  int swapped_dist = lab_distance(&img_lab_pixels[width * y2 + x2], &target_lab_pixels[width * y1 + x1])
                   + lab_distance(&img_lab_pixels[width * y1 + x1], &target_lab_pixels[width * y2 + x2]);

  return swapped_dist < dist;
}

void pixel_multiply_add(MagickPixelPacket *dest, PixelPacket *src, double mult) {
  dest->red += (double)GetPixelRed(src) * mult;
  dest->green += ((double)GetPixelGreen(src) - 32768) * mult;
  dest->blue += ((double)GetPixelBlue(src) - 32768) * mult;
}

#define min(x,y) (((x) < (y)) ? (x) : (y))
#define max(x,y) (((x) > (y)) ? (x) : (y))

double mpp_distance(MagickPixelPacket *a, MagickPixelPacket *b) {
  double l_diff = QuantumScale * (a->red - b->red),
         a_diff = QuantumScale * (a->green - b->green),
         b_diff = QuantumScale * (a->blue - b->blue);
  return (l_diff * l_diff + a_diff * a_diff + b_diff * b_diff);
}

void do_swap(PixelPacket *pix, int x1, int x2, int y1, int y2) {
  PixelPacket tmp = pix[width * y1 + x1];
  pix[width * y1 + x1] = pix[width * y2 + x2];
  pix[width * y2 + x2] = tmp;
}

int should_swap_dither(double detail, int x1, int x2, int y1, int y2) {
//  const InterpolatePixelMethod method = Average9InterpolatePixel;
  const InterpolatePixelMethod method = SplineInterpolatePixel;

  MagickPixelPacket img1, img2, img1s, img2s, target1, target2;
  GetMagickPixelPacket(img, &img1);
  GetMagickPixelPacket(img, &img2);
  GetMagickPixelPacket(img, &img1s);
  GetMagickPixelPacket(img, &img2s);
  GetMagickPixelPacket(target, &target1);
  GetMagickPixelPacket(target, &target2);
  InterpolateMagickPixelPacket(img, img_lab_view, method, x1, y1, &img1, e);
  InterpolateMagickPixelPacket(img, img_lab_view, method, x2, y2, &img2, e);
  InterpolateMagickPixelPacket(target, target_lab_view, method, x1, y1, &target1, e);
  InterpolateMagickPixelPacket(target, target_lab_view, method, x2, y2, &target2, e);
  do_swap(img_lab_pixels, x1, x2, y1, y2);
//  sync_pixels(img_wand);
  InterpolateMagickPixelPacket(img, img_lab_view, method, x1, y1, &img1s, e);
  InterpolateMagickPixelPacket(img, img_lab_view, method, x2, y2, &img2s, e);
  do_swap(img_lab_pixels, x1, x2, y1, y2);
//  sync_pixels(img_wand);

  pixel_multiply_add(&img1, &img_lab_pixels[width * y1 + x1], detail);
  pixel_multiply_add(&img2, &img_lab_pixels[width * y2 + x2], detail);
  pixel_multiply_add(&img1s, &img_lab_pixels[width * y2 + x2], detail);
  pixel_multiply_add(&img2s, &img_lab_pixels[width * y1 + x1], detail);
  pixel_multiply_add(&target1, &target_lab_pixels[width * y1 + x1], detail);
  pixel_multiply_add(&target2, &target_lab_pixels[width * y2 + x2], detail);

  double dist = mpp_distance(&img1, &target1)
              + mpp_distance(&img2, &target2);
  double swapped_dist = mpp_distance(&img1s, &target1)
                      + mpp_distance(&img2s, &target2);

  return swapped_dist + 1.0e-4 < dist;
}

int main(int argc, char *argv[]) {
  if (argc != 7) {
    fprintf(stderr, "Usage: %s source.png target.png dest nodither_pct dither_pct detail\n", argv[0]);
    return 1;
  }
  char *source_filename = argv[1];
  char *target_filename = argv[2];
  char *dest = argv[3];
  double nodither_pct = atof(argv[4]);
  double dither_pct = atof(argv[5]);
  double detail = atof(argv[6]) - 1;
  const int SWAPS_PER_LOOP = 1000000;
  int nodither_limit = ceil(SWAPS_PER_LOOP * nodither_pct / 100);
  int dither_limit = ceil(SWAPS_PER_LOOP * dither_pct / 100);
  int dither = 0, frame = 0;
  char outfile[256], cmdline[1024];
  sprintf(outfile, "out/%s.png", dest);

  MagickWandGenesis();
  e = AcquireExceptionInfo();
  source_wand = load_image(source_filename);
  source_pixels = get_pixels(source_wand);
  target_wand = load_image(target_filename);
  target_pixels = get_pixels(target_wand);
  img_wand = transfer_pixels();
  img_pixels = get_pixels(img_wand);
  target_lab_wand = image_to_lab(target_wand);
  target_lab_pixels = get_pixels(target_lab_wand);
  img_lab_wand = image_to_lab(img_wand);
  img_lab_pixels = get_pixels(img_lab_wand);
  img = GetImageFromMagickWand(img_lab_wand);
  target = GetImageFromMagickWand(target_lab_wand);
  img_lab_view = AcquireAuthenticCacheView(img, e);
  target_lab_view = AcquireAuthenticCacheView(target,e);
  CatchException(e);

  width = MagickGetImageWidth(img_wand);
  height = MagickGetImageHeight(img_wand);

  while (1) {
    int swaps_made = 0;
    for (int n = 0 ; n < SWAPS_PER_LOOP ; n++) {
      int x1 = rand() % width,
          x2 = rand() % width,
          y1 = rand() % height,
          y2 = rand() % height;

      int swap = dither ?
        should_swap_dither(detail, x1, x2, y1, y2)
        : should_swap(x1, x2, y1, y2);

      if (swap) {
        do_swap(img_pixels, x1, x2, y1, y2);
        do_swap(img_lab_pixels, x1, x2, y1, y2);
        swaps_made ++;
      }
    }

    sync_pixels(img_wand);
    if (!MagickWriteImages(img_wand, outfile, MagickTrue)) {
      ThrowWandException(img_wand);
    }
    img_pixels = get_pixels(img_wand);
    sprintf(cmdline, "cp out/%s.png anim/%s/%05i.png", dest, dest, frame++);
    system(cmdline);

    if (!dither && swaps_made < nodither_limit) {
      sprintf(cmdline, "cp out/%s.png out/%s-nodither.png", dest, dest);
      system(cmdline);
      dither = 1;
    } else if (dither && swaps_made < dither_limit)
      break;
  }

  return 0;
}

සමඟ සම්පාදනය කරන්න

gcc -std=gnu99 -O3 -march=native -ffast-math \
  -o transfer `pkg-config --cflags MagickWand` \
  transfer.c `pkg-config --libs MagickWand` -lm

ප්රතිපල

බොහෝ දුරට පර්ල් අනුවාදයට සමාන ය, තරමක් හොඳ ය, නමුත් ව්‍යතිරේක කිහිපයක් තිබේ. පොඟවා ගැනීම පොදුවේ අඩුය. කෑගැසීම -> තරු රාත්‍රියට "දැවෙන කන්ද" බලපෑමක් නැත, කැමරෝ අළු පික්සෙල් සමඟ අඩු පැහැයක් ගනී. මම හිතන්නේ පර්ල් අනුවාදයේ වර්ණ අවකාශ කේතයේ අඩු සන්තෘප්ත පික්සෙල් සහිත දෝෂයක් ඇත.

ඇමරිකානු ගොතික් පලත්

මොනා ලීසා පලත්

තරු රාත්‍රී පලත්

කෑගැසීමේ පලත්

ගෝලාකාර පලත්

මුස්තැන්ග් (කැමරෝ පලත්)

කැමරෝ (මුස්තැන්ග් පලත්)


ඔව් සර්, ඇත්තෙන්ම ඔබේ හොඳම දේ එයයි. C හි එය .5% නරක අතට හැරෙන්නේ ඇයි?
ආර්මැල්ක්

@RMalke තත්පර 20-30 අතර කාලයක් ධාවනය කිරීමට ඔහු ඉඩ දෙන විට එය වඩාත් නරක ය.
trlkly

කරුණාකර ඔබ භාවිතා වටිනාකම් පළ කළ හැකි nodither_pct, dither_pctසහ detailමෙම උදාහරණය තුල? මම ඔබේ වැඩසටහන විවිධ සංයෝජනයන් සමඟ ක්‍රියාත්මක කරමි, නමුත් මගේ රූප සඳහා ඒවා උප ප්‍රශස්ත බව පෙනේ, සහ පලත් ඔබේ ඒවාට සමීප වේ, එබැවින් ... කරුණාකර?
ඇන්ඩ්‍රේ කොස්ටිර්කා

@ AndreïKostyrka 0.1 0.1 1.6යනු මෙම රූප ජනනය කිරීමට මා භාවිතා කළ අගයන්ය.
හොබ්ස්

@ AndreïKostyrka 0.5 0.5 1.6හේතු යුතු පාහේ වේගවත් බොහෝ වේගය සමග හොඳ ගුණාත්මක ලෙස.
හොබ්ස්

23

දෝෂ ප්‍රචාරණය සහ වියළීම සමඟ එච්එස්එල් ආසන්නතම අගය

මගේ AllRGB රූප සඳහා භාවිතා කළ කේතයට මම සුළු අනුවර්තන කර ඇත . මෙය සැලසුම් කර ඇත්තේ මෙගාපික්සල් රූප 16 ක් සාධාරණ කාලයක් හා මතක සීමාවන් සහිතව සැකසීමටයි, එබැවින් එය සම්මත පුස්තකාලයේ නොමැති සමහර දත්ත ව්‍යුහ පන්ති භාවිතා කරයි; කෙසේ වෙතත්, මම දැනටමත් ඒවා විශාල කේතයක් ඇති බැවින් ඒවා අතහැර දමා ඇත.

AllRGB සඳහා මම රූපයේ ඇතැම් ප්‍රදේශවලට ප්‍රමුඛතාවය දෙන තරංග ආයාමයන් අතින් සකස් කරමි; මෙම මඟ පෙන්වනු නොලබන භාවිතය සඳහා, මම එක් තරංග ආයාමයක් තෝරා ගන්නවා, එය තුනෙන් පිරිසැලසුමේ රීතිය උපකල්පනය කරයි.

ඇමරිකානු ගොතික් මොනා ලිසා වෙතින් පලත් සමඟ ඇමරිකානු ගොතික් වෙතින් පලත් සමඟ මොනා ලීසා

මගේ ප්‍රියතම 36:

මොනා ලිසා වෙතින් පලත් සහිත ගංගාව

සම්පූර්ණ කාටිසියානු නිෂ්පාදනයක් (රූපය, පලත්)

package org.cheddarmonk.graphics;

import org.cheddarmonk.util.*;
import java.awt.Point;
import java.awt.image.*;
import java.io.File;
import java.util.Random;
import javax.imageio.ImageIO;

public class PaletteApproximator {
    public static void main(String[] args) throws Exception {
        // Adjust this to fine-tune for the areas which are most important.
        float[] waveletDefault = new float[] {0.5f, 0.333f, 0.5f, 0.5f, 1};

        generateAndSave(args[0], args[1], args[2], waveletDefault);
    }

    private static void generateAndSave(String paletteFile, String fileIn, String fileOut, float[]... wavelets) throws Exception {
        BufferedImage imgIn = ImageIO.read(new File(fileIn));
        int w = imgIn.getWidth(), h = imgIn.getHeight();

        int[] buf = new int[w * h];
        imgIn.getRGB(0, 0, w, h, buf, 0, w);

        SimpleOctTreeInt palette = loadPalette(paletteFile);
        generate(palette, buf, w, h, wavelets);

        // Masks for R, G, B, A.
        final int[] off = new int[]{0xff0000, 0xff00, 0xff, 0xff000000};
        // The corresponding colour model.
        ColorModel colourModel = ColorModel.getRGBdefault();
        DataBufferInt dbi = new DataBufferInt(buf, buf.length);
        Point origin = new Point(0, 0);
        WritableRaster raster = Raster.createPackedRaster(dbi, w, h, w, off, origin);
        BufferedImage imgOut = new BufferedImage(colourModel, raster, false, null);

        ImageIO.write(imgOut, "PNG", new File(fileOut));
    }

    private static SimpleOctTreeInt loadPalette(String paletteFile) throws Exception {
        BufferedImage img = ImageIO.read(new File(paletteFile));
        int w = img.getWidth(), h = img.getHeight();

        int[] buf = new int[w * h];
        img.getRGB(0, 0, w, h, buf, 0, w);

        // Parameters tuned for 4096x4096
        SimpleOctTreeInt octtree = new SimpleOctTreeInt(0, 1, 0, 1, 0, 1, 16, 12);
        for (int i = 0; i < buf.length; i++) {
            octtree.add(buf[i], transform(buf[i]));
        }

        return octtree;
    }

    private static void generate(SimpleOctTreeInt octtree, int[] buf, int w, int h, float[]... wavelets) {
        int m = w * h;

        LeanBinaryHeapInt indices = new LeanBinaryHeapInt();
        Random rnd = new Random();
        for (int i = 0; i < m; i++) {
            float x = (i % w) / (float)w, y = (i / w) / (float)w;

            float weight = 0;
            for (float[] wavelet : wavelets) {
                weight += wavelet[4] * Math.exp(-Math.pow((x - wavelet[0]) / wavelet[2], 2) - Math.pow((y - wavelet[1]) / wavelet[3], 2));
            }

            // Random element provides some kind of dither
            indices.insert(i, -weight + 0.2f * rnd.nextFloat());
        }

        // Error diffusion buffers.
        float[] errx = new float[m], erry = new float[m], errz = new float[m];

        for (int i = 0; i < m; i++) {
            int idx = indices.pop();
            int x = idx % w, y = idx / w;

            // TODO Bicubic interpolation? For the time being, prefer to scale the input image externally...
            float[] tr = transform(buf[x + w * y]);
            tr[0] += errx[idx]; tr[1] += erry[idx]; tr[2] += errz[idx];

            int pixel = octtree.nearestNeighbour(tr, 2);
            buf[x + y * w] = 0xff000000 | pixel;

            // Don't reuse pixels.
            float[] trPix = transform(pixel);
            boolean ok = octtree.remove(pixel, trPix);
            if (!ok) throw new IllegalStateException("Failed to remove from octtree");

            // Propagate error in 4 directions, not caring whether or not we've already done that pixel.
            // This will lose some error, but that might be a good thing.
            float dx = (tr[0] - trPix[0]) / 4, dy = (tr[1] - trPix[1]) / 4, dz = (tr[2] - trPix[2]) / 4;
            if (x > 0) {
                errx[idx - 1] += dx;
                erry[idx - 1] += dy;
                errz[idx - 1] += dz;
            }
            if (x < w - 1) {
                errx[idx + 1] += dx;
                erry[idx + 1] += dy;
                errz[idx + 1] += dz;
            }
            if (y > 0) {
                errx[idx - w] += dx;
                erry[idx - w] += dy;
                errz[idx - w] += dz;
            }
            if (y < h - 1) {
                errx[idx + w] += dx;
                erry[idx + w] += dy;
                errz[idx + w] += dz;
            }
        }
    }

    private static final float COS30 = (float)Math.sqrt(3) / 2;
    private static float[] transform(int rgb) {
        float r = ((rgb >> 16) & 0xff) / 255.f;
        float g = ((rgb >> 8) & 0xff) / 255.f;
        float b = (rgb & 0xff) / 255.f;

        // HSL cone coords
        float cmax = (r > g) ? r : g; if (b > cmax) cmax = b;
        float cmin = (r < g) ? r : g; if (b < cmin) cmin = b;
        float[] cone = new float[3];
        cone[0] = (cmax + cmin) / 2;
        cone[1] = 0.5f * (1 + r - (g + b) / 2);
        cone[2] = 0.5f * (1 + (g - b) * COS30);
        return cone;
    }
}

22

පයිතන්

කේතමය වශයෙන් හෝ ප්‍රති .ල අනුව නොවේ.

from blist import blist
from PIL import Image
import random

def randpop(colors):
    j = random.randrange(len(colors))
    return colors.pop(j)

colors = blist(Image.open('in1.png').getdata())
random.shuffle(colors)
target = Image.open('in2.png')

out = target.copy()
data = list(list(i) for i in out.getdata())

assert len(data) == len(colors)

w, h = out.size

coords = []
for i in xrange(h):
    for j in xrange(w):
        coords.append((i, j))

# Adjust color balance
dsum = [sum(d[i] for d in data) for i in xrange(3)]
csum = [sum(c[i] for c in colors) for i in xrange(3)]
adjust = [(csum[i] - dsum[i]) // len(data) for i in xrange(3)]
for i, j in coords:
    for k in xrange(3):
        data[i*w + j][k] += adjust[k]

random.shuffle(coords)

# larger value here gives better results but take longer
choose = 100
threshold = 10

done = set()
while len(coords):
    if not len(coords) % 1000:
        print len(coords) // 1000
    i, j = coords.pop()
    ind = i*w + j
    done.add(ind)
    t = data[ind]
    dmin = 255*3
    kmin = 0
    choices = []
    while colors and len(choices) < choose:
        k = len(choices)
        choices.append(randpop(colors))
        c = choices[-1]
        d = sum(abs(t[l] - c[l]) for l in xrange(3))
        if d < dmin:
            dmin = d
            kmin = k
            if d < threshold:
                break
    c = choices.pop(kmin)
    data[ind] = c
    colors.extend(choices)

    # Push the error to nearby pixels for dithering
    if ind + 1 < len(data) and ind + 1 not in done:
        ind2 = ind + 1
    elif ind + w < len(data) and ind + w not in done:
        ind2 = ind + w
    elif ind > 0 and ind - 1 not in done:
        ind2 = ind - 1
    elif ind - w > 0 and ind - w not in done:
        ind2 = ind - w
    else:
        ind2 = None
    if ind2 is not None:
        for k in xrange(3):
            err = abs(t[k] - c[k])
            data[ind2][k] += err

out.putdata(data)
out.save('out.png')

හැකි වැඩිදියුණු කිරීම්:

  • වඩා හොඳ වර්ණ නිවැරදි කිරීම?
  • වඩා හොඳ තත්ත්වයේ මෙට්‍රික්?
  • දෝෂය එකකට වඩා අවට ඇති සියලුම පික්සෙල් වෙත තල්ලු කරන්න

කැත (1-> 2): 1-> 2

ටිකක් හොඳයි (2-> 1): 2-> 1

විනීත (2-> 3): 2-> 3

නරක රේට්‍රේසර් වගේ (3-> 4): 3-> 4

වංචා කිරීම - ඉහළ භාගයේ ඇති සියලුම හොඳ පික්සල් භාවිතා කර තීන්ත ඉවරයි කියා කියන්න: 1-> 2


3
අන්තිම එක ... රසවත් අදහසක්. නමුත් තවමත් ඉහළට එන්නේ නැත.
ජෝන් ඩ්වොරක්

20

පයිතන් (kd-tree සහ දීප්තිය භාවිතා කිරීම)

හොඳ අභියෝගයක්. මම තීරණය කළා kd-tree ප්රවේශයක් සමඟ යන්න. එබැවින් kd-tree ප්රවේශයක් භාවිතා කිරීමේ මූලික අදහස නම්, එය පින්තූරයේ ඇති ස්ථානයට අනුව වර්ණ හා දීප්තිය බෙදීමයි.

එබැවින් kd-tree සඳහා පළමු වර්ග කිරීම රතු මත පදනම් වේ. එය සියලු වර්ණ දළ වශයෙන් සමාන රතු කණ්ඩායම් දෙකකට (ලා රතු සහ තද රතු) බෙදී යයි. ඊළඟට එය හරිතයන් දිගේ මෙම කොටස් දෙක බෙදයි. ඊළඟ නිල් සහ පසුව දීප්තිය සහ නැවත රතු. ගස ඉදිකරන තුරු එසේ කරන්න. මෙම ප්‍රවේශයේදී මම ප්‍රභව රූපය සහ ගමනාන්ත රූපය සඳහා kd-tree එකක් ඉදි කළෙමි. ඊට පසු මම ගස ප්‍රභවයේ සිට ගමනාන්තය දක්වා සිතියම් ගත කර ගමනාන්ත ගොනුවේ වර්ණ දත්ත නැවත ලියමි. සියලුම ප්‍රති results ල මෙහි දැක්වේ .

උදාහරණ කිහිපයක්:

මොනා ලීසා -> ඇමරිකානු ගොතික්

මොනාලිසා ඇමරිකානු ගොතික් (මොනා_ලිසා විලාසිතාව)

ඇමරිකානු ගොතික් -> මොනා ලීසා

ඇමරිකානු ගොතික් mona_lisa (ඇමරිකානු ගොතික් විලාසිතාව)

තරු රාත්‍රිය -> කෑගැසීම

තරු රාත්‍රිය තරු කෑගැසීම

කෑගැසීම -> තරු රාත්‍රිය

කෑගැසීම කෑගැසෙන තරු

දේදුන්න ගෝලාකාර

රූප විස්තරය මෙහි ඇතුළත් කරන්න මොනා ලිසා බෝල කෑගැසීමේ බෝල

@ කැල්වින්ගේ විනෝදාංශ චිත්‍රපට රාමු සාදන්නා භාවිතා කරමින් කෙටි චිත්‍රපටයක් මෙන්න:

රූප විස්තරය මෙහි ඇතුළත් කරන්න

දැන් කේතය සඳහා :-)

from PIL import Image

""" Computation of hue, saturation, luminosity.
Based on http://stackoverflow.com/questions/3732046/how-do-you-get-the-hue-of-a-xxxxxx-colour
"""
def rgbToLsh(t):
    r = t[0]
    g = t[1]
    b = t[2]
    r /= 255.
    g /= 255.
    b /= 255.
    vmax = max([r, g, b])
    vmin = min([r, g, b]);
    h = s = l = (vmax + vmin) / 2.;

    if (vmax == vmin):
        h = s = 0.  # achromatic
    else:
        d = vmax - vmin;
        if l > 0.5:
            s = d / (2. - vmax - vmin)
        else:
            s = d / (vmax + vmin);
        if vmax == r:
            if g<b: 
                m = 6. 
            else: 
                m = 0. 
            h = (g - b) / d + m
        elif vmax == g: 
            h = (b - r) / d + 2.
        elif vmax == b: 
            h = (r - g) / d + 4.
        h /= 6.;
    return [l,s,h];



""" KDTree implementation.
Based on https://code.google.com/p/python-kdtree/ 
"""
__version__ = "1r11.1.2010"
__all__ = ["KDTree"]

def square_distance(pointA, pointB):
    # squared euclidean distance
    distance = 0
    dimensions = len(pointA) # assumes both points have the same dimensions
    for dimension in range(dimensions):
        distance += (pointA[dimension] - pointB[dimension])**2
    return distance

class KDTreeNode():
    def __init__(self, point, left, right):
        self.point = point
        self.left = left
        self.right = right

    def is_leaf(self):
        return (self.left == None and self.right == None)

class KDTreeNeighbours():
    """ Internal structure used in nearest-neighbours search.
    """
    def __init__(self, query_point, t):
        self.query_point = query_point
        self.t = t # neighbours wanted
        self.largest_distance = 0 # squared
        self.current_best = []

    def calculate_largest(self):
        if self.t >= len(self.current_best):
            self.largest_distance = self.current_best[-1][1]
        else:
            self.largest_distance = self.current_best[self.t-1][1]

    def add(self, point):
        sd = square_distance(point, self.query_point)
        # run through current_best, try to find appropriate place
        for i, e in enumerate(self.current_best):
            if i == self.t:
                return # enough neighbours, this one is farther, let's forget it
            if e[1] > sd:
                self.current_best.insert(i, [point, sd])
                self.calculate_largest()
                return
        # append it to the end otherwise
        self.current_best.append([point, sd])
        self.calculate_largest()

    def get_best(self):
        return [element[0] for element in self.current_best[:self.t]]



class KDTree():
    """ KDTree implementation.

        Example usage:

            from kdtree import KDTree

            data = <load data> # iterable of points (which are also iterable, same length)
            point = <the point of which neighbours we're looking for>

            tree = KDTree.construct_from_data(data)
            nearest = tree.query(point, t=4) # find nearest 4 points
    """

    def __init__(self, data):

        self.data_listing = []
        def build_kdtree(point_list, depth):

            # code based on wikipedia article: http://en.wikipedia.org/wiki/Kd-tree
            if not point_list:
                return None

            # select axis based on depth so that axis cycles through all valid values
            axis = depth % 4 #len(point_list[0]) # assumes all points have the same dimension

            # sort point list and choose median as pivot point,
            # TODO: better selection method, linear-time selection, distribution
            point_list.sort(key=lambda point: point[axis])
            median = len(point_list)/2 # choose median

            # create node and recursively construct subtrees
            node = KDTreeNode(point=point_list[median],
                              left=build_kdtree(point_list[0:median], depth+1),
                              right=build_kdtree(point_list[median+1:], depth+1))

            # add point to listing                   
            self.data_listing.append(point_list[median])
            return node

        self.root_node = build_kdtree(data, depth=0)

    @staticmethod
    def construct_from_data(data):
        tree = KDTree(data)
        return tree

    def query(self, query_point, t=1):
        statistics = {'nodes_visited': 0, 'far_search': 0, 'leafs_reached': 0}

        def nn_search(node, query_point, t, depth, best_neighbours):
            if node == None:
                return

            #statistics['nodes_visited'] += 1

            # if we have reached a leaf, let's add to current best neighbours,
            # (if it's better than the worst one or if there is not enough neighbours)
            if node.is_leaf():
                #statistics['leafs_reached'] += 1
                best_neighbours.add(node.point)
                return

            # this node is no leaf

            # select dimension for comparison (based on current depth)
            axis = depth % len(query_point)

            # figure out which subtree to search
            near_subtree = None # near subtree
            far_subtree = None # far subtree (perhaps we'll have to traverse it as well)

            # compare query_point and point of current node in selected dimension
            # and figure out which subtree is farther than the other
            if query_point[axis] < node.point[axis]:
                near_subtree = node.left
                far_subtree = node.right
            else:
                near_subtree = node.right
                far_subtree = node.left

            # recursively search through the tree until a leaf is found
            nn_search(near_subtree, query_point, t, depth+1, best_neighbours)

            # while unwinding the recursion, check if the current node
            # is closer to query point than the current best,
            # also, until t points have been found, search radius is infinity
            best_neighbours.add(node.point)

            # check whether there could be any points on the other side of the
            # splitting plane that are closer to the query point than the current best
            if (node.point[axis] - query_point[axis])**2 < best_neighbours.largest_distance:
                #statistics['far_search'] += 1
                nn_search(far_subtree, query_point, t, depth+1, best_neighbours)

            return

        # if there's no tree, there's no neighbors
        if self.root_node != None:
            neighbours = KDTreeNeighbours(query_point, t)
            nn_search(self.root_node, query_point, t, depth=0, best_neighbours=neighbours)
            result = neighbours.get_best()
        else:
            result = []

        #print statistics
        return result


#List of files: 
files = ['JXgho.png','N6IGO.png','c5jq1.png','itzIe.png','xPAwA.png','y2VZJ.png']

#Loop over source files 
for im_orig in range(len(files)):
    srch = Image.open(files[im_orig])   #Open file handle 
    src = srch.load();                  #Load file  

    # Build data structure (R,G,B,lum,xpos,ypos) for source file
    srcdata =  [(src[i,j][0],src[i,j][1],src[i,j][2],rgbToLsh(src[i,j])[0],i,j) \
                     for i in range(srch.size[0]) \
                     for j in range(srch.size[1])]  

    # Build kd-tree for source
    srctree = KDTree.construct_from_data(srcdata)

    for im in range(len(files)):
        desh = Image.open(files[im])
        des = desh.load();

        # Build data structure (R,G,B,lum,xpos,ypos) for destination file
        desdata =  [(des[i,j][0],des[i,j][1],des[i,j][2],rgbToLsh(des[i,j]),i,j) \
                     for i in range(desh.size[0]) \
                     for j in range(desh.size[1])]  

        # Build kd-tree for destination
        destree = KDTree.construct_from_data(desdata)

        # Switch file mode
        desh.mode = srch.mode
        for k in range(len(srcdata)):
            # Get locations from kd-tree sorted data
            i   = destree.data_listing[k][-2]
            j   = destree.data_listing[k][-1]
            i_s = srctree.data_listing[k][-2]
            j_s = srctree.data_listing[k][-1]

            # Overwrite original colors with colors from source file 
            des[i,j] = src[i_s,j_s]

        # Save to disk  
        desh.save(files[im_orig].replace('.','_'+`im`+'.'))

මම මීට වසරකට පෙර මෙය දුටුවේ නැත, නමුත් එය තරමක් හොඳයි!
හොබ්ස්

16

පයිතන්

බෝලය පෙරළීම සඳහා, මෙන්න මගේම සරල හා වේදනාකාරී මන්දගාමී පිළිතුරකි.

import Image

def countColors(image):
    colorCounts = {}
    for color in image.getdata():
        if color in colorCounts:
            colorCounts[color] += 1
        else:
            colorCounts[color] = 1
    return colorCounts

def colorDist(c1, c2):
    def ds(c1, c2, i):
        return (c1[i] - c2[i])**2
    return (ds(c1, c2, 0) + ds(c1, c2, 1) + ds(c1, c2, 2))**0.5

def findClosestColor(palette, color):
    closest = None
    minDist = (3*255**2)**0.5
    for c in palette:
        dist = colorDist(color, c)
        if dist < minDist:
            minDist = dist
            closest = c
    return closest

def removeColor(palette, color):
    if palette[color] == 1:
        del palette[color]
    else:
        palette[color] -= 1

def go(paletteFile, sourceFile):
    palette = countColors(Image.open(paletteFile).convert('RGB'))
    source = Image.open(sourceFile).convert('RGB')
    copy = Image.new('RGB', source.size)
    w, h = copy.size

    for x in range(w):
        for y in range(h):
            c = findClosestColor(palette, source.getpixel((x, y)))
            removeColor(palette, c)
            copy.putpixel((x, y), c)
        print x #print progress
    copy.save('copy.png')

#the respective file paths go here
go('../ag.png', '../r.png')

ප්‍රභවයේ ඇති සෑම පික්සෙල් සඳහාම එය RGB වර්ණ කියුබයට ආසන්නතම තලයේ භාවිතා නොකරන පික්සෙල් සොයයි. එය මූලික වශයෙන් Quincunx හි ඇල්ගොරිතමයට සමාන නමුත් අහඹු බවක් සහ වෙනස් වර්ණ සංසන්දනාත්මක ශ්‍රිතයක් නොමැත.

සමාන වර්ණවල ක්ෂය වීම නිසා රූපයේ දකුණු පැත්තේ අඩු විස්තරයක් ඇති බැවින් මම වමේ සිට දකුණට ගමන් කරන බව ඔබට පැවසිය හැකිය.

ඇමරිකානු ගොතික් සිට ගඟ

ඇමරිකානු ගොතික් සිට ගඟ

රේන්බෝ ගෝලාකාර මොනා ලීසා

රේන්බෝ ගෝලාකාර මොනා ලීසා


1
ම්ම්. ලීසා ටිකක් කහ පැහැති වේ ...
tomsmeding

4
ඇමරිකානු ගොතික් සිට වමේ සිට 'දකුණට' දකුණට 'වියුක්තය' =)
දෝෂය

12

හස්කල්

මෙම විසඳුම නිරාකරණය කිරීමට පෙර මම ආසන්නතම අසල්වැසි සෙවීම් භාවිතා කරමින් වෙනස් ප්‍රවේශයන් කිහිපයක් උත්සාහ කළෙමි (එය ඇත්ත වශයෙන්ම මගේ පළමු අදහස විය). මම මුලින්ම පික්සල් ආකෘති YCbCr බවට පරිවර්තනය කර ඒවායේ පික්සල් දත්ත අඩංගු ලැයිස්තු දෙකක් සාදමි. එවිට, දීප්තියේ අගයට ප්‍රමුඛතාවය ලබා දෙමින් ලැයිස්තු වර්ග කරනු ලැබේ. ඊට පසු, මම ආදාන රූපයේ වර්ග කළ පික්සල් ලැයිස්තුව පලත් පිංතූරයට ආදේශ කර, පසුව එය මුල් අනුපිළිවෙලට යොමු කර නව රූපයක් තැනීමට භාවිතා කරමි.

module Main where

import System.Environment    (getArgs)
import System.Exit           (exitSuccess, exitFailure)
import System.Console.GetOpt (getOpt, ArgOrder(..), OptDescr(..), ArgDescr(..))
import Data.List             (sortBy)

import Codec.Picture
import Codec.Picture.Types

import qualified Data.Vector as V

main :: IO ()
main = do
    (ioOpts, _) <- getArgs >>= getOpts
    opts        <- ioOpts
    image       <- loadImage $ imageFile opts
    palette     <- loadImage $ paletteFile opts
    case swapPalette image palette of
      Nothing -> do
          putStrLn "Error: image and palette dimensions do not match"
          exitFailure
      Just img ->
          writePng (outputFile opts) img

swapPalette :: Image PixelYCbCr8 -> Image PixelYCbCr8 -> Maybe (Image PixelRGB8)
swapPalette img pal
    | area1 == area2 =
        let cmpCr (_, (PixelYCbCr8 _ _ r1)) (_, (PixelYCbCr8 _ _ r2)) = r1 `compare` r2
            cmpCb (_, (PixelYCbCr8 _ c1 _)) (_, (PixelYCbCr8 _ c2 _)) = c1 `compare` c2
            cmpY  (_, (PixelYCbCr8 y1 _ _)) (_, (PixelYCbCr8 y2 _ _)) = y2 `compare` y1
            w       = imageWidth  img
            h       = imageHeight img
            imgData = sortBy cmpY $ sortBy cmpCr $ sortBy cmpCb $ zip [1 :: Int ..] $ getPixelList img
            palData = sortBy cmpY $ sortBy cmpCr $ sortBy cmpCb $ zip [1 :: Int ..] $ getPixelList pal
            newData = zipWith (\(n, _) (_, p) -> (n, p)) imgData palData
            pixData = map snd $ sortBy (\(n1, _) (n2, _) -> n1 `compare` n2) newData
            dataVec = V.reverse $ V.fromList pixData
        in  Just $ convertImage $ generateImage (lookupPixel dataVec w h) w h
    | otherwise = Nothing
    where area1 = (imageWidth img) * (imageHeight img)
          area2 = (imageWidth pal) * (imageHeight pal)

lookupPixel :: V.Vector PixelYCbCr8 -> Int -> Int -> Int -> Int -> PixelYCbCr8
lookupPixel vec w h x y = vec V.! i
    where i = flattenIndex w h x y

getPixelList :: Image PixelYCbCr8 -> [PixelYCbCr8]
getPixelList img = foldl (\ps (x, y) -> (pixelAt img x y):ps) [] coords
    where coords = [(x, y) | x <- [0..(imageWidth img) - 1], y <- [0..(imageHeight img) - 1]]

flattenIndex :: Int -> Int -> Int -> Int -> Int
flattenIndex _ h x y = y + (x * h)

-------------------------------------------------
-- Command Line Option Functions
-------------------------------------------------

getOpts :: [String] -> IO (IO Options, [String])
getOpts args = case getOpt Permute options args of
    (opts, nonOpts, []) -> return (foldl (>>=) (return defaultOptions) opts, nonOpts)
    (_, _, errs)        -> do
        putStrLn $ concat errs
        printUsage
        exitFailure

data Options = Options
  { imageFile   :: Maybe FilePath
  , paletteFile :: Maybe FilePath
  , outputFile  :: FilePath
  }

defaultOptions :: Options
defaultOptions = Options
  { imageFile   = Nothing
  , paletteFile = Nothing
  , outputFile  = "out.png"
  }

options :: [OptDescr (Options -> IO Options)]
options = [ Option ['i'] ["image"]   (ReqArg setImage   "FILE") "",
            Option ['p'] ["palette"] (ReqArg setPalette "FILE") "",
            Option ['o'] ["output"]  (ReqArg setOutput  "FILE") "",
            Option ['v'] ["version"] (NoArg showVersion)        "",
            Option ['h'] ["help"]    (NoArg exitPrintUsage)     ""]

setImage :: String -> Options -> IO Options
setImage image opts = return $ opts { imageFile = Just image }

setPalette :: String -> Options -> IO Options
setPalette palette opts = return $ opts { paletteFile = Just palette }

setOutput :: String -> Options -> IO Options
setOutput output opts = return $ opts { outputFile = output }

printUsage :: IO ()
printUsage = do
    putStrLn "Usage: repix [OPTION...] -i IMAGE -p PALETTE [-o OUTPUT]"
    putStrLn "Rearrange pixels in the palette file to closely resemble the given image."
    putStrLn ""
    putStrLn "-i, --image    specify the image to transform"
    putStrLn "-p, --palette  specify the image to use as the palette"
    putStrLn "-o, --output   specify the output image file"
    putStrLn ""
    putStrLn "-v, --version  display version information and exit"
    putStrLn "-h, --help     display this help and exit"

exitPrintUsage :: a -> IO Options
exitPrintUsage _ = do
    printUsage
    exitSuccess

showVersion :: a -> IO Options
showVersion _ = do
    putStrLn "Pixel Rearranger v0.1"
    exitSuccess

-------------------------------------------------
-- Image Loading Util Functions
-------------------------------------------------

loadImage :: Maybe FilePath -> IO (Image PixelYCbCr8)
loadImage Nothing     = do
    printUsage
    exitFailure
loadImage (Just path) = do
    rdImg <- readImage path
    case rdImg of
      Left err -> do
          putStrLn err
          exitFailure
      Right img -> getRGBImage img

getRGBImage :: DynamicImage -> IO (Image PixelYCbCr8)
getRGBImage dynImg =
    case dynImg of
      ImageYCbCr8 img -> return img
      ImageRGB8   img -> return $ convertImage img
      ImageY8     img -> return $ convertImage (promoteImage img :: Image PixelRGB8)
      ImageYA8    img -> return $ convertImage (promoteImage img :: Image PixelRGB8)
      ImageCMYK8  img -> return $ convertImage (convertImage img :: Image PixelRGB8)
      ImageRGBA8  img -> return $ convertImage (pixelMap dropTransparency img :: Image PixelRGB8)
      _               -> do
          putStrLn "Error: incompatible image type."
          exitFailure

ප්රතිපල

මගේ වැඩසටහන මඟින් නිපදවන රූප අනෙක් විසඳුම් වලට වඩා විචිත්‍රවත් වන අතර එය විශාල areas න ප්‍රදේශ හෝ ශ්‍රේණි සමඟ හොඳින් කටයුතු නොකරයි.

මෙන්න සම්පූර්ණ ඇල්බමයට සබැඳියක්.

ඇමරිකානු ගොතික් -> මොනා ලීසා

මොනා ලීසා -> ඇමරිකානු ගොතික්

ගෝලාකාර -> මොනා ලීසා

කෑගැසීම -> තරු රාත්‍රිය

කෑගැසීම -> ගෝල


3
(ගෝලාකාර -> මොනා ලිසා) මතට බැසීමට මම කැමතියි, නමුත් (කෑගැසීම -> ගෝලාකාර) මත ඇති එම කැත කෞතුක වස්තු කොහෙන්ද?
ජෝන් ඩ්වොරක්

1
කෞතුක වස්තු යනු මගේ ඇල්ගොරිතම පික්සල් වර්ග කරන ආකාරයෙහි අතුරු ආබාධයකි. මේ මොහොතේ, එක් එක් පික්සෙල් වල රතු-වෙනස වර්ග කිරීමේ පියවරේ නිල්-වෙනසට වඩා ප්‍රමුඛතාවයක් ඇත, එයින් අදහස් කරන්නේ ආදාන රූපයේ සමාන වර්ණ පැලට් රූපයට වඩා වෙනස් වර්ණ සමඟ සැසඳිය හැකි බවයි. කෙසේ වෙතත්, මෙම බලපෑමම ගෝලාකාර -> මොනා ලිසා වැනි රූපවල පෙනෙන්නට තිබෙන බව මට විශ්වාසයි, එබැවින් මම එය තබා ගැනීමට තීරණය කළෙමි.
ChaseC

9

ජාවා

Quincunx වෙතින් පෙර ජාවා පිළිතුරෙන් ආශ්වාදයක්

     package paletteswap;

import java.awt.Point;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import javax.imageio.ImageIO;

public class Test
{
    public static class Bits
    {

        public static BitSet convert( int value )
        {
            BitSet bits = new BitSet();
            int index = 0;
            while ( value != 0L )
            {
                if ( value % 2 != 0 )
                {
                    bits.set( index );
                }
                ++index;
                value = value >>> 1;
            }
            return bits;
        }

        public static int convert( BitSet bits )
        {
            int value = 0;
            for ( int i = 0; i < bits.length(); ++i )
            {
                value += bits.get( i ) ? ( 1 << i ) : 0;
            }
            return value;
        }
    }

    public static void main( String[] args ) throws IOException
    {
        BufferedImage source = ImageIO.read( resource( "river.png" ) ); // My names
                                                                            // for the
                                                                            // files
        BufferedImage palette = ImageIO.read( resource( "farmer.png" ) );
        BufferedImage result = rearrange( source, palette );
        ImageIO.write( result, "png", resource( "result.png" ) );
    }

    public static BufferedImage rearrange( BufferedImage source, BufferedImage palette )
    {
        BufferedImage result = new BufferedImage( source.getWidth(), source.getHeight(), BufferedImage.TYPE_INT_RGB );

        // This creates a list of points in the Source image.
        // Then, we shuffle it and will draw points in that order.
        List<Point> samples = getPoints( source.getWidth(), source.getHeight() );
        Collections.sort( samples, new Comparator<Point>()
        {

            @Override
            public int compare( Point o1, Point o2 )
            {
                int c1 = getRGB( source, o1.x, o1.y );
                int c2 = getRGB( source, o2.x, o2.y );
                return c1 -c2;
            }
        } );

        // Create a list of colors in the palette.
        List<Integer> colors = getColors( palette );

        while ( !samples.isEmpty() )
        {
            Point currentPoint = samples.remove( 0 );
            int sourceAtPoint = getRGB( source, currentPoint.x, currentPoint.y );
            int colorIndex = binarySearch( colors, sourceAtPoint );
            int bestColor = colors.remove( colorIndex );
            setRGB( result, currentPoint.x, currentPoint.y, bestColor );
        }
        return result;
    }

    public static int unpack( int rgbPacked )
    {
        BitSet packed = Bits.convert( rgbPacked );
        BitSet rgb = Bits.convert( 0 );
        for (int i=0; i<8; i++)
        {
            rgb.set( i,    packed.get( i*3 )  );
            rgb.set( i+16,    packed.get( i*3+1 )  );
            rgb.set( i+8,    packed.get( i*3+2 )  );
        }
        return Bits.convert( rgb);
    }

    public static int pack( int rgb )
    {
        int myrgb = rgb & 0x00FFFFFF;

        BitSet bits = Bits.convert( myrgb );
        BitSet packed = Bits.convert( 0 );

        for (int i=0; i<8; i++)
        {
            packed.set( i*3,    bits.get( i )  );
            packed.set( i*3+1,  bits.get( i+16 )  );
            packed.set( i*3+2,  bits.get( i+8 )  );
        }
        return Bits.convert( packed);

    }

    public static int getRGB( BufferedImage image, int x, int y )
    {
        return pack( image.getRGB( x, y ) );
    }

    public static void setRGB( BufferedImage image, int x, int y, int color )
    {
        image.setRGB( x, y, unpack( color ) );
    }

    public static List<Point> getPoints( int width, int height )
    {
        List<Point> points = new ArrayList<>( width * height );
        for ( int x = 0; x < width; x++ )
        {
            for ( int y = 0; y < height; y++ )
            {
                points.add( new Point( x, y ) );
            }
        }
        return points;
    }

    public static List<Integer> getColors( BufferedImage img )
    {
        int width = img.getWidth();
        int height = img.getHeight();
        List<Integer> colors = new ArrayList<>( width * height );
        for ( int x = 0; x < width; x++ )
        {
            for ( int y = 0; y < height; y++ )
            {
                colors.add( getRGB( img, x, y ) );
            }
        }
        Collections.sort( colors );
        return colors;
    }

    public static int binarySearch( List<Integer> toSearch, int obj )
    {
        int index = toSearch.size() >> 1;
        for ( int guessChange = toSearch.size() >> 2; guessChange > 0; guessChange >>= 1 )
        {
            int value = toSearch.get( index );
            if ( obj == value )
            {
                return index;
            }
            else if ( obj < value )
            {
                index -= guessChange;
            }
            else
            {
                index += guessChange;
            }
        }
        return index;
    }

    public static File resource( String fileName )
    { // This method is here solely
        // for my ease of use (I put
        // the files under <Project
        // Name>/Resources/ )
        return new File( System.getProperty( "user.home" ) + "/pictureswap/" + fileName );
    }
}

මොනා ලිසා -> ගොවීන්

රූප විස්තරය මෙහි ඇතුළත් කරන්න

එය කුමක්ද යන්න අහඹු ලෙස වෙනුවට ඒවායේ තීව්‍රතාවයෙන් ප්‍රතිස්ථාපනය කළ යුතු කරුණු වර්ග කරයි.


8

රූබි

දළ විශ්ලේෂණය:

ඇත්තෙන්ම සරල ප්‍රවේශයක්, නමුත් හොඳ ප්‍රති results ල ලැබෙන බව පෙනේ:

  1. පලත් රැගෙන ඉලක්කය ගන්න, ඒවායේ පික්සෙල් දෙකම යම් ශ්‍රිතයකින් වර්ග කරන්න; මේවා “යොමු” අරා ලෙස හඳුන්වන්න. මම එච්එස්එල්ඒ අනුව වර්ග කිරීමට තෝරාගෙන ඇත, නමුත් දීප්තියට වඩා සන්තෘප්තියට වඩා හියු (හෝ "එල්එස්එච්ඒ")
  2. ඉලක්කගත රූපයේ එක් එක් පික්සෙල් හරහා නැවත සැකසීම, ඉලක්කගත යොමු අරාව තුළ එය වර්ග කර ඇත්තේ කොතැනදැයි සොයා ගැනීම සහ පලත් යොමු අරාවෙහි එකම දර්ශකයට වර්ග කර ඇති පලතුරෙන් පික්සෙල් ලබා ගැනීමෙන් ප්‍රතිදාන රූපය සාදන්න.

කේතය:

require 'rubygems'
require 'chunky_png'
require 'rmagick' # just for the rgba => hsla converter, feel free to use something lighter-weight you have on hand

def pixel_array_for_image(image)
  # [r, b, g, a]
  image.pixels.map{|p| ChunkyPNG::Color.to_truecolor_alpha_bytes(p)}
end

def sorted_pixel_references(pixel_array)
  pixel_array.map{|a| yield(a)}.map.with_index.sort_by(&:first).map(&:last)
end

def sort_by_lsha(pixel_array)
  sorted_pixel_references(pixel_array) {|p|
    # feel free to drop in any sorting function you want here!
    hsla = Magick::Pixel.new(*p).to_hsla # [h, s, l, a]
    [hsla[2], hsla[1], hsla[0], hsla[3]]
  }
end

def make_target_out_of_palette(target_filename, palette_filename, output_filename)
  puts "making #{target_filename} out of #{palette_filename}"

  palette = ChunkyPNG::Image.from_file(palette_filename)
  target = ChunkyPNG::Image.from_file(target_filename)
  puts "  loaded images"

  palette_array = pixel_array_for_image(palette)
  target_array = pixel_array_for_image(target)
  puts "  have pixel arrays"

  palette_spr = sort_by_lsha(palette_array)
  target_spr = sort_by_lsha(target_array)
  puts "  have sorted-pixel reference arrays"

  output = ChunkyPNG::Image.new(target.dimension.width, target.dimension.height, ChunkyPNG::Color::TRANSPARENT)
  (0...target_array.count).each { |index|
    spr_index = target_spr.index(index)
    index_in_palette = palette_spr[spr_index]
    palette_pixel = palette_array[index_in_palette]
    index_as_x = (index % target.dimension.width)
    index_as_y = (index / target.dimension.width)
    output[index_as_x, index_as_y] = ChunkyPNG::Color.rgba(*palette_pixel)
  }
  output.save(output_filename)
  puts "  saved to #{output_filename}"
end

palette_filename, target_filename, output_filename = ARGV
make_target_out_of_palette(target_filename, palette_filename, output_filename)

ප්රතිපල:

http://imgur.com/a/Iu7Ds

කැපී පෙනෙන අවස්ථා:

තරු රාත්‍රිය කෑගැසීමෙන් සාදන ලදී ඇමරිකානු ගොතික් මොනා ලිසා වලින් සාදන ලදී මොනා ලීසා ගංගා ඡායාරූපයෙන් සාදන ලදී ස්ටාරි නයිට් වලින් සාදන ලද ගංගා ඡායාරූපය


2
එක් එක් රූපය සඳහා මූලාශ්‍රය එකතු කළ හැකිද?
ප්ලාස්මා එච්

7

පර්ල්

මෙන්න තරමක් සරල ප්‍රවේශයකි. මගේ මැක්බුක් ප්‍රෝ හි රූප යුගලයකට රාමු 100 ක් උත්පාදනය කිරීමට තත්පර පහක් පමණ ගත වේ .

මෙහි අදහස වන්නේ පික්සල් දෙකෙහිම සහ පලත් රූප බිටු 24 ඇසුරුම් කළ RGB මගින් වර්ග කිරීම සහ ප්‍රභවයේ වර්ණ අනුපිළිවෙලින් වර්ණවලින් ආදේශ කිරීමයි.

#!/usr/bin/env perl

use 5.020; # just because
use strict;
use warnings;

use Const::Fast;
use GD;
GD::Image->trueColor(1);

use Path::Class;

const my $COLOR => 0;
const my $COORDINATES => 1;
const my $RGB => 2;
const my $ANIMATION_FRAMES => 100;

const my %MASK => (
    RED => 0x00ff0000,
    GREEN => 0x0000ff00,
    BLUE => 0x000000ff,
);

run(@ARGV);

sub run {
    unless (@_ == 2) {
        die "Need source and palette images\n";
    }
    my $source_file = file(shift)->resolve;
    my $palette_file = file(shift)->resolve;

    my $source = GD::Image->new("$source_file")
        or die "Failed to create source image from '$source_file'";
    my $palette = GD::Image->new("$palette_file")
        or die "Failed to create palette image from '$palette_file'";

    my %source =  map { $_ => $source->$_ } qw(width height);
    my %palette = map { $_ => $palette->$_ } qw(width height);
    my ($frame_prefix) = ($source_file->basename =~ /\A([^.]+)/);

    unless (
        (my $source_area = $source{width} * $source{height}) <=
        (my $palette_area = $palette{width} * $source{height})
    ) {
        die "Source area ($source_area) is greater than palette area ($palette_area)";
    }

    my ($last_frame, $png) = recreate_source_image_from_palette(
        \%source,
        get_source_pixels( get_pixels_by_color($source, \%source) ),
        get_palette_colors( get_pixels_by_color($palette, \%palette) ),
        sub { save_frame($frame_prefix, @_) }
    );

    save_frame($frame_prefix, $last_frame, $png);
    return;
}

sub save_frame {
    my $frame_prefix = shift;
    my $frame = shift;
    my $png = shift;
    file(
        sprintf("${frame_prefix}-%d.png", $frame)
    )->spew(iomode => '>:raw', $$png);
    return;
}

sub recreate_source_image_from_palette {
    my $dim = shift;
    my $source_pixels = shift;
    my $palette_colors = shift;
    my $callback = shift;
    my $frame = 0;

    my %colors;
    $colors{$_} = undef for @$palette_colors;

    my $gd = GD::Image->new($dim->{width}, $dim->{height}, 1);
    for my $x (keys %colors) {
          $colors{$x} = $gd->colorAllocate(unpack_rgb($x));
    }

    my $period = sprintf '%.0f', @$source_pixels / $ANIMATION_FRAMES;
    for my $i (0 .. $#$source_pixels) {
        $gd->setPixel(
            @{ $source_pixels->[$i] },
            $colors{ $palette_colors->[$i] }
        );
        if ($i % $period == 0) {
            $callback->($frame, \ $gd->png);
            $frame += 1;
        }
    }
    return ($frame, \ $gd->png);
}

sub get_palette_colors { [ map sprintf('%08X', $_->[$COLOR]), @{ $_[0] } ] }

sub get_source_pixels { [ map $_->[$COORDINATES], @{ $_[0] } ] }

sub get_pixels_by_color {
    my $gd = shift;
    my $dim = shift;
    return [
        sort { $a->[$COLOR] <=> $b->[$COLOR] }
        map {
            my $y = $_;
            map {
                [ pack_rgb( $gd->rgb( $gd->getPixel($_, $y) ) ), [$_, $y] ];
            } 0 .. $dim->{width}
        } 0 .. $dim->{height}
    ];
}

sub pack_rgb { $_[0] << 16 | $_[1] << 8 | $_[2] }

sub unpack_rgb {
    my ($r, $g, $b) = map $MASK{$_} & hex($_[0]), qw(RED GREEN BLUE);
    return ($r >> 16, $g >> 8, $b);
}

ප්‍රතිදානය

තරු රාත්‍රී පලත් භාවිතා කර කෑගසන්න

තරු රාත්‍රී පලත් භාවිතා කර කෑගසන්න

මොනා ලිසා වර්ණ භාවිතා කරන ඇමරිකානු ගොතික්

මොනා ලිසා වර්ණ භාවිතා කරන ඇමරිකානු ගොතික්

ස්ක්‍රීම් වර්ණ භාවිතා කරමින් මොනා ලීසා

ස්ක්‍රීම් වර්ණ භාවිතා කරමින් මොනා ලීසා

කිරිගරු colors වර්ණ භාවිතා කරන ගංගාව

කිරිගරු colors වර්ණ භාවිතා කරන ගංගාව

සජීවිකරණ

මම කම්මැලි විය, එබැවින් මම සජීවිකරණ යූ ටියුබ් වෙත දැමුවෙමි: මොනා ලිසා ස්ටාර්රි නයිට් සහ ඇමරිකානු ගොතික් වල වර්ණ භාවිතා කරමින් මොනා ලිසා වෙතින් වර්ණ භාවිතා කරයි.


7

පයිතන්

මේ දිනවල වැඩ කිරීමේදී බොහෝ විට පැමිණෙමින් පවතින බැවින් කේත ගොල්ෆ් ක්‍රීඩාව භාර ගැනීමට සහ මගේ පයිතන් චොප්ස් වැඩ කිරීමට එය නිදහසට කරුණක් ලෙස භාවිතා කිරීමට මම සිතුවෙමි. මම ඇල්ගොරිතම කිහිපයක් හරහා දිව ගියෙමි, වර්ණ කිහිපයක් උත්සාහ කිරීමට හා ප්‍රශස්තිකරණය කිරීමට O (n ^ 2) සහ O (nlog (n)) කාලයද ඇතුළුව, නමුත් මෙය පරිගණකමය වශයෙන් මිල අධික බවත් ඇත්ත වශයෙන්ම ඉතා අල්ප බවත් පැහැදිලි විය. පෙනෙන ප්‍රති .ලය කෙරෙහි බලපෑම. එබැවින් පහත දැක්වෙන්නේ O (n) කාලය තුළ (මූලික වශයෙන් ක්ෂණිකව මගේ පද්ධතියේ) වැඩ කරන දේවල් පිළිබඳව වඩාත් වැදගත් දෘශ්‍ය මූලද්‍රව්‍යය (දීප්තිය) සාධාරණ ලෙස නිවැරදිව ලබා ගන්නා අතර ක්‍රෝමා භූමියට හැකි තැනට ඉඩ සලසයි.

from PIL import Image
def check(palette, copy):
    palette = sorted(palette.getdata())
    copy = sorted(copy.getdata())
    print "Master says it's good!" if copy == palette else "The master disapproves."

def GetLuminance(pixel):
    # Extract the pixel channel data
    b, g, r = pixel
    # and used the standard luminance curve to get luminance.
    return .3*r+.59*g+.11*b

print "Putting pixels on the palette..."
# Open up the image and get all of the pixels out of it. (Memory intensive!)
palette = Image.open("2.png").convert(mode="RGB")

pixelsP = [] # Allocate the array
width,height = palette.size # Unpack the image size
for y in range(height): # Scan the lines
    for x in range(width): # within the line, scan the pixels
        curpixel = palette.getpixel((x,y)) # get the pixel
        pixelsP.append((GetLuminance(curpixel),curpixel)) # and add a (luminance, color) tuple to the array.


# sort the pixels by the calculated luminescence
pixelsP.sort()

print "Getting the reference picture..."
# Open up the image and get all of the pixels out of it. (Memory intensive!)
source = Image.open("6.png").convert(mode="RGB")
pixelsR = [] # Allocate the array
width,height = source.size # Unpack the image size
for y in range(height): # Scan the lines
    for x in range(width): # within the line, scan the pixels
        curpixel = source.getpixel((x,y)) # get the pixel
        pixelsR.append((GetLuminance(curpixel),(x,y))) # and add a (luminance, position) tuple

# Sort the Reference pixels by luminance too
pixelsR.sort()

# Now for the neat observation. Luminance matters more to humans than chromanance,
# given this then we want to match luminance as well as we can. However, we have
# a finite luminance distribution to work with. Since we can't change that, it's best
# just to line the two images up, sorted by luminance, and just simply assign the
# luminance directly. The chrominance will be all kinds of whack, but fixing that
# by way of loose sorting possible chrominance errors takes this algorithm from O(n)
# to O(n^2), which just takes forever (trust me, I've tried it.)

print "Painting reference with palette..."
for p in range(len(pixelsP)): # For each pixel in the palette
    pl,pixel = pixelsP[p] # Grab the pixel from the palette
    l,cord = pixelsR[p] # Grab the location from the reference
    source.putpixel(cord,pixel) # and assign the pallet pixel to the refrence pixels place

print "Applying fixative..."
# save out the result.
source.save("o.png","PNG")

print "Handing it to the master to see if he approves..."
check(palette, source)
print "Done!"

අවසාන ප්‍රති result ලය සමහර පිළිවෙලට ඇත. කෙසේ වෙතත්, පින්තූරවල දීප්තිමත් ආලෝක බෙදාහැරීම් තිබේ නම්, දියුණු හා වියළීමකින් තොරව කළ හැකි බොහෝ දේ නොමැත, එය යම් අවස්ථාවක දී කළ යුතු සිත්ගන්නා සුළු දෙයක් විය හැකි නමුත්, එය සංක්ෂිප්ත කාරණයක් ලෙස මෙහි බැහැර කර ඇත.

හැම දෙයක්ම -> මොනා ලීසා

ඇමරිකානු ගොතික් -> මොනා ලීසා තරු රාත්‍රිය -> මොනා ලීසා කෑගැසීම -> මොනා ලීසා ගඟ -> මොනා ලීසා ගෝලාකාර -> මොනා ලීසා

මොනා ලීසා -> ගෝලාකාර

මොනා ලීසා -> ගෝලාකාර


6

ගණිතය - අහඹු ප්‍රේරණය

අදහස

ප්‍රභව රූපයේ පික්සෙල් දෙකක් තෝරන්න සහ ගමනාන්ත රූපයේ දෝෂය අඩු වන්නේ දැයි පරීක්ෂා කරන්න. දේශීය අවම වළක්වා ගැනීම සඳහා අපි කුඩා අහඹු අංකයක් (-d | + d) ප්‍රති result ලයට එකතු කරමු. නැවත නැවත කරන්න. වේගය සඳහා මෙය එකවර පික්සල් 10000 සමඟ කරන්න.

එය ටිකක් මාකෝව් අහඹු දාමයක් වගේ. සමානුපාතික ඇනලීකරණයට සමාන ප්‍රශස්තිකරණ ක්‍රියාවලියේදී අහඹු බව අඩු කිරීම හොඳය.

කේතය

colorSpace = "RGB";
\[Delta] = 0.05;
ClearAll[loadImgur, imgToList, listToImg, improveN, err, rearrange, \
rearrangeImg]
loadImgur[tag_] := 
 RemoveAlphaChannel@
  Import["http://i.stack.imgur.com/" <> tag <> ".png"]
imgToList[img_] := Flatten[ImageData[ColorConvert[img, colorSpace]], 1]
listToImg[u_, w_] := Image[Partition[u, w], ColorSpace -> colorSpace]
err[{x_, y_, z_}] := x^2 + y^2 + z^2
improveN[a_, t_, n_] := Block[{i, j, ai, aj, ti, tj},
  {i, j} = Partition[RandomSample[Range@Length@a, 2 n], n];
  ai = a[[i]];
  aj = a[[j]];
  ti = t[[i]];
  tj = t[[j]];
  ReplacePart[
   a, (#1 -> #3) & @@@ 
    Select[Transpose[{i, 
       err /@ (ai - ti) + err /@ (aj - tj) - err /@ (ai - tj) - 
        err /@ (aj - ti) + RandomReal[\[Delta]^2 {-1, +1}, n], aj}], #[[2]] > 0 &]]
  ]
rearrange[ua_, ub_, iterations_: 100] := Block[{tmp = ua},
  Do[tmp = improveN[tmp, ub, Floor[.1 Length@ua]];, {i, iterations}]; 
  tmp]
rearrangeImg[a_, b_, iterations_: 100] := With[{imgdst = loadImgur[b]},
  listToImg[rearrange[
    RandomSample@imgToList@loadImgur[a],
    imgToList@imgdst, iterations], First@ImageDimensions@imgdst]]
rearrangeImg["JXgho","itzIe"]

ප්රතිපල

ගොතික් සිට මොනා ලිසා දක්වා. වමේ: LAB වර්ණ අවකාශය භාවිතා කිරීම (ඩෙල්ටා = 0). දකුණ: RBG වර්ණ අවකාශය භාවිතා කිරීම (ඩෙල්ටා = 0) img7 img8

ගොතික් සිට මොනා ලිසා දක්වා. වමේ: RGB වර්ණ අවකාශය, ඩෙල්ටා = 0.05. දකුණ: RGB වර්ණ අවකාශය, ඩෙල්ටා = 0.15. img9 img10

පහත රූපවල RGB වර්ණ අවකාශය සහ ඩෙල්ටා = 0 සහිත හුවමාරු 3,500,000 ක් සඳහා සජීවිකරණ පෙන්වයි.

img1 img2 img3 img4 img5 img6


ඇඩිට්සුගේ මාර්ගය මෙන් පෙනේ, නමුත් මම ඔබේ ප්‍රති .ල බලාපොරොත්තුවෙන් සිටිමි.
ලීෆ්

5

සැකසීම

ප්‍රභවය සහ පලත් එක පැත්තකින් පෙන්වා ඇති අතර, පික්සල් වල සජීවීකරණයක් ඇත.

පේළියේ int i = chooseIndexIncremental(); , ඔබට chooseIndex*පික්සෙල් තේරීමේ අනුපිළිවෙල බැලීමට කාර්යයන් වෙනස් කළ හැකිය .

int scanRate = 20; // pixels per frame

// image filenames
String source = "N6IGO.png";
String palette = "JXgho.png";

PImage src, pal, res;
int area;
int[] lut;
boolean[] processed;
boolean[] taken;
int count = 0;

void start() {
  //size(800, 600);

  src = loadImage(source);
  pal = loadImage(palette);

  size(src.width + pal.width, max(src.height, pal.height));

  src.loadPixels();
  pal.loadPixels();

  int areaSrc = src.pixels.length;
  int areaPal = pal.pixels.length;

  if (areaSrc != areaPal) {
    println("Areas mismatch: src: " + areaSrc + ", pal: " + areaPal);
    return;
  }

  area = areaSrc;

  println("Area: " + area);

  lut = new color[area];
  taken = new boolean[area];
  processed = new boolean[area];

  randomSeed(1);
}

void draw() {
  background(0);
  image(src, 0, 0);
  image(pal, src.width, 0);

  for (int k = 0; k < scanRate; k ++)
  if (count < area) {
    // choose from chooseIndexRandom, chooseIndexSkip and chooseIndexIncremental
    int i = chooseIndexIncremental();
    process(i);

    processed[i] = true;
    count ++;
  }
}

int chooseIndexRandom() {
  int i = 0;
  do i = (int) random(area); while (processed[i]);
  return i;
}

int chooseIndexSkip(int n) {
  int i = (n * count) % area;
  while (processed[i] || i >= area) i = (int) random(area);
  return i;
}

int chooseIndexIncremental() {
  return count;
}

void process(int i) {
  lut[i] = findPixel(src.pixels[i]);
  taken[lut[i]] = true;

  src.loadPixels();
  src.pixels[i] = pal.pixels[lut[i]];
  src.updatePixels();

  pal.loadPixels();
  pal.pixels[lut[i]] = color(0);
  pal.updatePixels();

  stroke(src.pixels[i]);
  int sy = i / src.width;
  int sx = i % src.width;

  int j = lut[i];
  int py = j / pal.width;
  int px = j % pal.width;
  line(sx, sy, src.width + px, py);
}

int findPixel(color c) {
  int best;
  do best = (int) random(area); while (taken[best]);
  float bestDist = colorDist(c, pal.pixels[best]);

  for (int k = 0; k < area; k ++) {
    if (taken[k]) continue;
    color c1 = pal.pixels[k];
    float dist = colorDist(c, c1);
    if (dist < bestDist) {
      bestDist = dist;
      best = k;
    }
  }
  return best;
}

float colorDist(color c1, color c2) {
  return S(red(c1) - red(c2)) + S(green(c1) - green(c2)) + S(blue(c1) - blue(c2));
}

float S(float x) { return x * x; }

ඇමරිකානු ගොතික් -> මොනා ලීසා, වර්ධක

වර්ධනාත්මක

ඇමරිකානු ගොතික් -> මොනා ලීසා, අහඹු

අහඹු


2
ඔබ දේදුන්න ගෝලාකාර තලය භාවිතා කරන්නේ නම් එය පෙනෙන්නේ කෙසේද?
ඔබේ මෝඩයන්ට හොඳින් සලකන්න

5

සී-ෂාප්

නව / ආකර්ෂණීය අදහස් නැත, නමුත් මම එය උත්සාහ කර බැලීමට සිතුවෙමි. වර්ණවලට වඩා සන්තෘප්තියට වඩා දීප්තියට ප්‍රමුඛතාවය දෙමින් පික්සල් සරලව වර්ග කරන්න. කේතය එහි වටිනාකම කුමක් වුවත් සාධාරණ ලෙස කෙටි ය.

සංස්කරණය කරන්න: ඊටත් වඩා කෙටි අනුවාදයක් එක් කරන ලදි

using System;
using System.Drawing;
using System.Collections.Generic;

class Program
{
    static void Main(string[] args)
    {
        Bitmap sourceImg = new Bitmap("TheScream.png"),
            arrangImg = new Bitmap("StarryNight.png"),
            destImg = new Bitmap(arrangImg.Width, arrangImg.Height);

        List<Pix> sourcePixels = new List<Pix>(), arrangPixels = new List<Pix>();

        for (int i = 0; i < sourceImg.Width; i++)
            for (int j = 0; j < sourceImg.Height; j++)
                sourcePixels.Add(new Pix(sourceImg.GetPixel(i, j), i, j));

        for (int i = 0; i < arrangImg.Width; i++)
            for (int j = 0; j < arrangImg.Height; j++)
                arrangPixels.Add(new Pix(arrangImg.GetPixel(i, j), i, j));

        sourcePixels.Sort();
        arrangPixels.Sort();

        for (int i = 0; i < arrangPixels.Count; i++)
            destImg.SetPixel(arrangPixels[i].x,
                             arrangPixels[i].y,
                             sourcePixels[i].col);

        destImg.Save("output.png");
    }
}

class Pix : IComparable<Pix>
{
    public Color col;
    public int x, y;
    public Pix(Color col, int x, int y)
    {
        this.col = col;
        this.x = x;
        this.y = y;
    }

    public int CompareTo(Pix other)
    {
        return(int)(255 * 255 * 255 * (col.GetBrightness() - other.col.GetBrightness())
                + (255 * (col.GetHue() - other.col.GetHue()))
                + (255 * 255 * (col.GetSaturation() - other.col.GetSaturation())));
    }
}

නියැදිය:

රූප විස්තරය මෙහි ඇතුළත් කරන්න

+

රූප විස්තරය මෙහි ඇතුළත් කරන්න

=

රූප විස්තරය මෙහි ඇතුළත් කරන්න


5

ජාවා

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import javax.imageio.ImageIO;

/**
 *
 * @author Quincunx
 */
public class PixelRearrangerMK2 {

    public static void main(String[] args) throws IOException {
        BufferedImage source = ImageIO.read(resource("Raytraced Spheres.png"));
        BufferedImage palette = ImageIO.read(resource("American Gothic.png"));
        BufferedImage result = rearrange(source, palette);
        ImageIO.write(result, "png", resource("result.png"));
        validate(palette, result);
    }

    public static BufferedImage rearrange(BufferedImage source, BufferedImage palette) {
        List<Color> sColors = Color.getColors(source);
        List<Color> pColors = Color.getColors(palette);
        Collections.sort(sColors);
        Collections.sort(pColors);

        BufferedImage result = new BufferedImage(source.getWidth(), source.getHeight(), BufferedImage.TYPE_INT_RGB);
        Iterator<Color> sIter = sColors.iterator();
        Iterator<Color> pIter = pColors.iterator();

        while (sIter.hasNext()) {
            Color s = sIter.next();
            Color p = pIter.next();

            result.setRGB(s.x, s.y, p.rgb);
        }
        return result;
    }

    public static class Color implements Comparable {
        int x, y;
        int rgb;
        double hue;

        private int r, g, b;

        public Color(int x, int y, int rgb) {
            this.x = x;
            this.y = y;
            this.rgb = rgb;
            r = (rgb & 0xFF0000) >> 16;
            g = (rgb & 0x00FF00) >> 8;
            b = rgb & 0x0000FF;
            hue = Math.atan2(Math.sqrt(3) * (g - b), 2 * r - g - b);
        }

        @Override
        public int compareTo(Object o) {
            Color c = (Color) o;
            return hue < c.hue ? -1 : hue == c.hue ? 0 : 1;
        }

        public static List<Color> getColors(BufferedImage img) {
            List<Color> result = new ArrayList<>();
            for (int y = 0; y < img.getHeight(); y++) {
                for (int x = 0; x < img.getWidth(); x++) {
                    result.add(new Color(x, y, img.getRGB(x, y)));
                }
            }
            return result;
        }
    }

    //Validation and util methods follow
    public static void validate(BufferedImage palette, BufferedImage result) {
        List<Integer> paletteColors = getColorsAsInt(palette);
        List<Integer> resultColors = getColorsAsInt(result);
        Collections.sort(paletteColors);
        Collections.sort(resultColors);
        System.out.println(paletteColors.equals(resultColors));
    }

    public static List<Integer> getColorsAsInt(BufferedImage img) {
        int width = img.getWidth();
        int height = img.getHeight();
        List<Integer> colors = new ArrayList<>(width * height);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                colors.add(img.getRGB(x, y));
            }
        }
        Collections.sort(colors);
        return colors;
    }

    public static File resource(String fileName) {
        return new File(System.getProperty("user.dir") + "/Resources/" + fileName);
    }
}

මෙන්න සම්පූර්ණයෙන්ම වෙනස් අදහසක්. මම එක් එක් රූපයේ වර්ණ ලැයිස්තුවක් සාදමි, පසුව මම වර්ණ අනුව වර්ග කරමි, එය විකිපීඩියාවේ සූත්‍රයෙන් ගණනය කෙරේ:

රූප විස්තරය මෙහි ඇතුළත් කරන්න

මගේ අනෙක් පිළිතුර මෙන් නොව මෙය අතිශයින් වේගවත් ය. වලංගු කිරීම ඇතුළුව තත්පර 2 ක් පමණ ගත වේ.

ප්රති result ලය සමහර වියුක්ත කලාවකි. මෙන්න පින්තූර කිහිපයක් (බැලීමට / සිට බැලීමට මූසිකය):

රූප විස්තරය මෙහි ඇතුළත් කරන්න රූප විස්තරය මෙහි ඇතුළත් කරන්න රූප විස්තරය මෙහි ඇතුළත් කරන්න රූප විස්තරය මෙහි ඇතුළත් කරන්න රූප විස්තරය මෙහි ඇතුළත් කරන්න රූප විස්තරය මෙහි ඇතුළත් කරන්න රූප විස්තරය මෙහි ඇතුළත් කරන්න


5
යමක් ප්රිඩේටර් o_O දකිනවා ඇති බව පෙනේ
eithed

මේවා තරමක් බියජනක ය, නමුත් ඒවා ඇත්ත වශයෙන්ම නිවැරදි ය!
කැල්වින්ගේ විනෝදාංශ

1
@ කැල්වින්ගේ විනෝදාංශ මෙය බියජනක වන්නේ කෙසේද? මම එය අලංකාරය ලෙස හඳුන්වමි.
ජස්ටින්

3
ඔවුන්ගේ මුහුණු හිස් හා විනෝදජනකයි ... නමුත් ඔවුන්ට හොල්මන් සුන්දරත්වයක් ඇත.
කැල්වින්ගේ විනෝදාංශ

1
ගෝල නියමයි.
siledh

5

පයිතන්

හොඳයි, මම තීරණය කළා මගේ විසඳුම පළ කිරීමට, මම ඒ සඳහා කාලය ගත කළ නිසා. අත්යවශ්යයෙන්ම, මම සිතුවේ රූපවල අමු පික්සල් දත්ත ලබා ගැනීම, දත්ත දීප්තියෙන් වර්ග කිරීම, ඉන්පසු එකම දර්ශකයේ අගයන් නව රූපයකට දැමීමයි. මම දීප්තිය ගැන මගේ අදහස වෙනස් කර, ඒ වෙනුවට දීප්තිය භාවිතා කළෙමි. මට මේ සමඟ හොඳ ප්‍රති results ල ලැබුණා.

from PIL import Image
from optparse import OptionParser


def key_func(arr):
    # Sort the pixels by luminance
    r = 0.2126*arr[0] + 0.7152*arr[1] + 0.0722*arr[2]
    return r


def main():
    # Parse options from the command line
    parser = OptionParser()
    parser.add_option("-p", "--pixels", dest="pixels",
                      help="use pixels from FILE", metavar="FILE")
    parser.add_option("-i", "--input", dest="input", metavar="FILE",
                      help="recreate FILE")
    parser.add_option("-o", "--out", dest="output", metavar="FILE",
                      help="output to FILE", default="output.png")

    (options, args) = parser.parse_args()

    if not options.pixels or not options.input:
        raise Exception("Missing arguments. See help for more info.")

    # Load the images
    im1 = Image.open(options.pixels)
    im2 = Image.open(options.input)

    # Get the images into lists
    px1 = list(im1.getdata())
    px2 = list(im2.getdata())
    w1, h1 = im1.size
    w2, h2 = im2.size

    if w1*h1 != w2*h2:
        raise Exception("Images must have the same number of pixels.")

    # Sort the pixels lists by luminance
    px1_s = sorted(px1, key=key_func)
    px2_s = sorted(px2, key=key_func)

    # Create an array of nothing but black pixels
    arr = [(0, 0, 0)]*w2*h2

    # Create a dict that contains a list of locations with pixel value as key
    # This speeds up the process a lot, since before it was O(n^2)
    locations_cache = {}
    for index, val in enumerate(px2):
        v = str(val)
        if v in locations_cache:
            locations_cache[v].append(index)
        else:
            locations_cache[v] = [index]

    # Loop through each value of the sorted pixels
    for index, val in enumerate(px2_s):
        # Find the original location of the pixel
        # v = px2.index(val)
        v = locations_cache[str(val)].pop(0)
        # Set the value of the array at the given location to the pixel of the
        # equivalent luminance from the source image
        arr[v] = px1_s[index]
        # v2 = px1.index(px1_s[index])
        # Set the value of px2 to an arbitrary value outside of the RGB range
        # This prevents duplicate pixel locations
        # I would use "del px2[v]", but it wouldn't work for some reason
        px2[v] = (512, 512, 512)
        # px1[v2] = (512, 512, 512)
        # Print the percent progress
        print("%f%%" % (index/len(px2)*100))
        """if index % 500 == 0 or index == len(px2_s)-1:
            if h1 > h2:
                size = (w1+w2, h1)
            else:
                size = (w1+w2, h2)
            temp_im1 = Image.new("RGB", im2.size)
            temp_im1.putdata(arr)

            temp_im2 = Image.new("RGB", im1.size)
            temp_im2.putdata(px1)

            temp_im3 = Image.new("RGB", size)
            temp_im3.paste(temp_im1, (0, 0))
            temp_im3.paste(temp_im2, (w2, 0))
            temp_im3.save("still_frames/img_%04d.png" % (index/500))"""

    # Save the image
    im3 = Image.new('RGB', im2.size)
    im3.putdata(arr)
    im3.save(options.output)

if __name__ == '__main__':
    main()

ප්රතිපල

ප්‍රති .ල ගැන මම සෑහීමකට පත්වුණා. එය හරහා මා තැබූ සියලුම රූප සඳහා එය නිරන්තරයෙන් ක්‍රියාත්මක වන බවක් පෙනෙන්නට තිබුණි.

ස්ක්‍රීම් පික්සල් සහිත තරු රාත්‍රිය

කෑගැසීම + තරු රාත්‍රිය

රේන්බෝ පික්සෙල් සමඟ තරු රාත්‍රිය

දේදුන්න + තරු රාත්‍රිය

තරු රාත්‍රී පික්සල් සහිත දේදුන්න

තරු රාත්‍රිය + දේදුන්න

ස්ක්‍රීම් පික්සෙල් සමඟ මොනා ලීසා

කෑගැසීම + මොනා ලීසා

තරු රාත්‍රී පික්සල් සහිත ගංගාව

තරු රාත්‍රිය + ගඟ

ඇමරිකානු ගොතික් පික්සෙල් සමඟ මොනා ලීසා

ගොතික් + මොනා ලීසා

චෙවි පික්සෙල් සමඟ මුස්තැන්ග්

මගේ දෘඩාංග අවහිරතා සැලකිල්ලට ගෙන මම රූප අඩු කළ යුතුව තිබුණි, නමුත් හොඳයි.

චෙවි + මුස්තැන්ග්

මුස්තැන් පික්සෙල් සමඟ චෙවි

මුස්තැන්ග් + චෙවි

රේන්බෝ පික්සල් සහිත ගංගාව

දේදුන්න + ගඟ

රේන්බෝ පික්සෙල් සමඟ මොනා ලීසා

දේදුන්න + මොනා ලීසා

රේන්බෝ පික්සෙල් සමඟ ඇමරිකානු ගොතික්

දේදුන්න + ගොතික්


යාවත්කාලීන කිරීම මම තවත් පින්තූර කිහිපයක් එකතු කර ඇති අතර මෙන්න සජීවිකරණ කිහිපයක්. පළමුවැන්න මගේ ක්‍රමය ක්‍රියාත්මක වූ ආකාරය පෙන්වන අතර දෙවැන්න ස්ක්‍රිප්ට් එක භාවිතා කිරීමයි @ කැල්වින් හොබීස් පළ කළේය.

මගේ ක්‍රමය

@ කැල්වින් හොබීස් පිටපත


යාවත්කාලීන කිරීම 2 මම පික්සෙල්වල දර්ශක ඒවායේ වර්ණයෙන් ගබඩා කරන නියෝගයක් එක් කළෙමි. මෙමඟින් ස්ක්‍රිප්ට් මාර්ගය වඩාත් කාර්යක්ෂම විය. මුල් පිටපත බැලීමට, සංශෝධන ඉතිහාසය පරීක්ෂා කරන්න.


5

සී ++ 11

අවසානයේදී, මම සාපේක්ෂව සරල නිර්ණායක කෑදර ඇල්ගොරිතමයක් මත පදිංචි වුණෙමි. මෙය තනි නූල්, නමුත් මගේ යන්ත්‍රයේ තත්පර 4 කට වඩා වැඩි කාලයක් හිසකෙස් වලින් දිව යයි.

මූලික ඇල්ගොරිතම ක්‍රියාත්මක වන්නේ දීප්තිය අඩු කිරීමෙන් පලතේ සහ ඉලක්කගත රූපයේ ඇති සියලුම පික්සෙල් වර්ග කිරීමෙනි (L හි L a b * ). ඉන්පසු, ඇණවුම් කරන ලද එක් එක් ඉලක්කගත පික්සෙල් සඳහා, එය පලතුරේ පළමු ඇතුළත් කිරීම් 75 න් ආසන්නතම තරගය සොයනු ඇත, CIEDE2000 දුර මෙට්‍රික් හි වර්ග භාවිතා කරමින් ඉලක්කයට ගැළපෙන පලත් වර්ණවල දීප්තිය සමඟ. (CIEDE2000 ක්‍රියාත්මක කිරීම සහ නිදොස්කරණය කිරීම සඳහා, මෙම පිටුව ඉතා ප්‍රයෝජනවත් විය). හොඳම ගැලපීම පසුව ප්‍රස්තාරයෙන් ඉවත් කර ප්‍රති result ලයට පවරා ඇති අතර ඇල්ගොරිතම ඉලක්ක රූපයේ ඊළඟ සැහැල්ලු පික්සෙල් වෙත යයි.

ඉලක්කය සහ පලත් යන දෙකටම වර්ග කළ දීප්තිය භාවිතා කිරීමෙන්, ප්‍රති result ලයේ සමස්ත දීප්තිය (වඩාත්ම දෘශ්‍යමාන මූලද්‍රව්‍යය) ඉලක්කයට හැකි තරම් සමීපව ගැලපෙන බව අපි සහතික කරමු. ඇතුළත් කිරීම් 75 කින් යුත් කුඩා කවුළුවක් භාවිතා කිරීමෙන් නිවැරදි දීප්තියේ ගැළපෙන වර්ණයක් සොයා ගැනීමට හොඳ අවස්ථාවක් ලැබේ. එකක් නොමැති නම්, වර්ණය අක්‍රිය වනු ඇත, නමුත් අවම වශයෙන් දීප්තිය අනුකූල විය යුතුය. එහි ප්‍රති As ලයක් ලෙස, සුදුමැලි වර්ණ හොඳින් නොගැලපෙන විට එය තරමක් සුන්දර ලෙස පිරිහෙයි.

කේතය

මෙය සම්පාදනය කිරීම සඳහා ඔබට ImageMagick ++ සංවර්ධන පුස්තකාල අවශ්‍ය වේ. එය සම්පාදනය කිරීම සඳහා කුඩා CMake ගොනුවක් ද පහත දැක්වේ.

palette.cpp

#include <Magick++.h>
#include <algorithm>
#include <functional>
#include <utility>
#include <set>

using namespace std;
using namespace Magick;

struct Lab
{
    PixelPacket rgb;
    float L, a, b;

    explicit Lab(
        PixelPacket rgb )
        : rgb( rgb )
    {
        auto R_srgb = static_cast< float >( rgb.red ) / QuantumRange;
        auto G_srgb = static_cast< float >( rgb.green ) / QuantumRange;
        auto B_srgb = static_cast< float >( rgb.blue ) / QuantumRange;
        auto R_lin = R_srgb < 0.04045f ? R_srgb / 12.92f :
            powf( ( R_srgb + 0.055f ) / 1.055f, 2.4f );
        auto G_lin = G_srgb < 0.04045f ? G_srgb / 12.92f :
            powf( ( G_srgb + 0.055f ) / 1.055f, 2.4f );
        auto B_lin = B_srgb < 0.04045f ? B_srgb / 12.92f :
            powf( ( B_srgb + 0.055f ) / 1.055f, 2.4f );
        auto X = 0.4124f * R_lin + 0.3576f * G_lin + 0.1805f * B_lin;
        auto Y = 0.2126f * R_lin + 0.7152f * G_lin + 0.0722f * B_lin;
        auto Z = 0.0193f * R_lin + 0.1192f * G_lin + 0.9502f * B_lin;
        auto X_norm = X / 0.9505f;
        auto Y_norm = Y / 1.0000f;
        auto Z_norm = Z / 1.0890f;
        auto fX = ( X_norm > 216.0f / 24389.0f ?
                    powf( X_norm, 1.0f / 3.0f ) :
                    X_norm * ( 841.0f / 108.0f ) + 4.0f / 29.0f );
        auto fY = ( Y_norm > 216.0f / 24389.0f ?
                    powf( Y_norm, 1.0f / 3.0f ) :
                    Y_norm * ( 841.0f / 108.0f ) + 4.0f / 29.0f );
        auto fZ = ( Z_norm > 216.0f / 24389.0f ?
                    powf( Z_norm, 1.0f / 3.0f ) :
                    Z_norm * ( 841.0f / 108.0f ) + 4.0f / 29.0f );
        L = 116.0f * fY - 16.0f;
        a = 500.0f * ( fX - fY );
        b = 200.0f * ( fY - fZ );
    }

    bool operator<(
        Lab const that ) const
    {
        return ( L > that.L ? true :
                 L < that.L ? false :
                 a > that.a ? true :
                 a < that.a ? false :
                 b > that.b );
    }

    Lab clampL(
        Lab const that ) const
    {
        auto result = Lab( *this );
        if ( result.L > that.L )
            result.L = that.L;
        return result;
    }

    float cieDe2000(
        Lab const that,
        float const k_L = 1.0f,
        float const k_C = 1.0f,
        float const k_H = 1.0f ) const
    {
        auto square = []( float value ){ return value * value; };
        auto degs = []( float rad ){ return rad * 180.0f / 3.14159265359f; };
        auto rads = []( float deg ){ return deg * 3.14159265359f / 180.0f; };
        auto C_1 = hypot( a, b );
        auto C_2 = hypot( that.a, that.b );
        auto C_bar = ( C_1 + C_2 ) * 0.5f;
        auto C_bar_7th = square( square( C_bar ) ) * square( C_bar ) * C_bar;
        auto G = 0.5f * ( 1.0f - sqrtf( C_bar_7th / ( C_bar_7th + 610351562.0f ) ) );
        auto a_1_prime = ( 1.0f + G ) * a;
        auto a_2_prime = ( 1.0f + G ) * that.a;
        auto C_1_prime = hypot( a_1_prime, b );
        auto C_2_prime = hypot( a_2_prime, that.b );
        auto h_1_prime = C_1_prime == 0.0f ? 0.0f : degs( atan2f( b, a_1_prime ) );
        if ( h_1_prime < 0.0f )
            h_1_prime += 360.0f;
        auto h_2_prime = C_2_prime == 0.0f ? 0.0f : degs( atan2f( that.b, a_2_prime ) );
        if ( h_2_prime < 0.0f )
            h_2_prime += 360.0f;
        auto delta_L_prime = that.L - L;
        auto delta_C_prime = C_2_prime - C_1_prime;
        auto delta_h_prime =
            C_1_prime * C_2_prime == 0.0f ? 0 :
            fabs( h_2_prime - h_1_prime ) <= 180.0f ? h_2_prime - h_1_prime :
            h_2_prime - h_1_prime > 180.0f ? h_2_prime - h_1_prime - 360.0f :
            h_2_prime - h_1_prime + 360.0f;
        auto delta_H_prime = 2.0f * sqrtf( C_1_prime * C_2_prime ) *
            sinf( rads( delta_h_prime * 0.5f ) );
        auto L_bar_prime = ( L + that.L ) * 0.5f;
        auto C_bar_prime = ( C_1_prime + C_2_prime ) * 0.5f;
        auto h_bar_prime =
            C_1_prime * C_2_prime == 0.0f ? h_1_prime + h_2_prime :
            fabs( h_1_prime - h_2_prime ) <= 180.0f ? ( h_1_prime + h_2_prime ) * 0.5f :
            h_1_prime + h_2_prime < 360.0f ? ( h_1_prime + h_2_prime + 360.0f ) * 0.5f :
            ( h_1_prime + h_2_prime - 360.0f ) * 0.5f;
        auto T = ( 1.0f
                   - 0.17f * cosf( rads( h_bar_prime - 30.0f ) )
                   + 0.24f * cosf( rads( 2.0f * h_bar_prime ) )
                   + 0.32f * cosf( rads( 3.0f * h_bar_prime + 6.0f ) )
                   - 0.20f * cosf( rads( 4.0f * h_bar_prime - 63.0f ) ) );
        auto delta_theta = 30.0f * expf( -square( ( h_bar_prime - 275.0f ) / 25.0f ) );
        auto C_bar_prime_7th = square( square( C_bar_prime ) ) *
            square( C_bar_prime ) * C_bar_prime;
        auto R_C = 2.0f * sqrtf( C_bar_prime_7th / ( C_bar_prime_7th + 610351562.0f ) );
        auto S_L = 1.0f + ( 0.015f * square( L_bar_prime - 50.0f ) /
                            sqrtf( 20.0f + square( L_bar_prime - 50.0f ) ) );
        auto S_C = 1.0f + 0.045f * C_bar_prime;
        auto S_H = 1.0f + 0.015f * C_bar_prime * T;
        auto R_T = -sinf( rads( 2.0f * delta_theta ) ) * R_C;
        return (
            square( delta_L_prime / ( k_L * S_L ) ) +
            square( delta_C_prime / ( k_C * S_C ) ) +
            square( delta_H_prime / ( k_H * S_H ) ) +
            R_T * delta_C_prime * delta_H_prime / ( k_C * S_C * k_H * S_H ) );
    }

};

Image read_image(
    char * const filename )
{
    auto result = Image( filename );
    result.type( TrueColorType );
    result.matte( true );
    result.backgroundColor( Color( 0, 0, 0, QuantumRange ) );
    return result;
}

template< typename T >
multiset< T > map_image(
    Image const &image,
    function< T( unsigned, PixelPacket ) > const transform )
{
    auto width = image.size().width();
    auto height = image.size().height();
    auto result = multiset< T >();
    auto pixels = image.getConstPixels( 0, 0, width, height );
    for ( auto index = 0; index < width * height; ++index, ++pixels )
        result.emplace( transform( index, *pixels ) );
    return result;
}

int main(
    int argc,
    char **argv )
{
    auto palette = map_image(
        read_image( argv[ 1 ] ),
        function< Lab( unsigned, PixelPacket ) >(
            []( unsigned index, PixelPacket rgb ) {
                return Lab( rgb );
            } ) );

    auto target_image = read_image( argv[ 2 ] );
    auto target_colors = map_image(
        target_image,
        function< pair< Lab, unsigned >( unsigned, PixelPacket ) >(
            []( unsigned index, PixelPacket rgb ) {
                return make_pair( Lab( rgb ), index );
            } ) );

    auto pixels = target_image.setPixels(
        0, 0,
        target_image.size().width(),
        target_image.size().height() );
    for ( auto &&target : target_colors )
    {
        auto best_color = palette.begin();
        auto best_difference = 1.0e38f;
        auto count = 0;
        for ( auto candidate = palette.begin();
              candidate != palette.end() && count < 75;
              ++candidate, ++count )
        {
            auto difference = target.first.cieDe2000(
                candidate->clampL( target.first ) );
            if ( difference < best_difference )
            {
                best_color = candidate;
                best_difference = difference;
            }
        }
        pixels[ target.second ] = best_color->rgb;
        palette.erase( best_color );
    }
    target_image.syncPixels();
    target_image.write( argv[ 3 ] );

    return 0;
}

CMakeList.txt

cmake_minimum_required( VERSION 2.8.11 )
project( palette )
add_executable( palette palette.cpp)
find_package( ImageMagick COMPONENTS Magick++ )
if( ImageMagick_FOUND )
    include_directories( ${ImageMagick_INCLUDE_DIRS} )
    target_link_libraries( palette ${ImageMagick_LIBRARIES} )
endif( ImageMagick_FOUND )

ප්‍රති ult ලය

සම්පූර්ණ ඇල්බමය මෙහි ඇත. පහත දැක්වෙන ප්‍රති results ල අතුරින්, මගේ ප්‍රියතමයන් බොහෝ විට ඇමරිකානු ගොතික් සමඟ මොනා ලිසා පලත් සහ ස්ටාර්රි නයිට් විත් ස්පියර්ස් පලත් වේ.

ඇමරිකානු ගොතික් පැලට්

මොනා ලීසා පැලට්

පැලට් ගංගාව

Scream Palette

ගෝලාකාර පලට්

තරු රාත්‍රී පලත්


මෙය අපූරුයි! මෙය කොතරම් වේගවත් කළ හැකිද යන්න ගැන ඔබ සිතන්නේ කුමක්ද? තථ්‍ය කාලය සඳහා අවස්ථාවක් තිබේද, එනම් සාමාන්‍ය දෘඩාංග සඳහා 60fps?
danijar

4

සී ++

කෙටිම කේතය නොව තනි-නූල් සහ ප්‍රශස්තිකරණය නොතකා 'ක්ෂණිකව' පිළිතුර ජනනය කරයි. ප්‍රති .ල ගැන මම සතුටු වෙමි.

මම පික්සෙල් වර්ග දෙකක් ලැයිස්තුගත කරමි, එක් එක් රූපය සඳහා එකක්, සහ වර්ග කිරීම පදනම් වන්නේ 'දීප්තියේ' බර මත ය. දීප්තිය ගණනය කිරීම සඳහා මම 100% කොළ, 50% රතු සහ 10% නිල් භාවිතා කරමි, එය මිනිස් ඇසට බර (වැඩි හෝ අඩු). මම පසුව ප්‍රභව රූපයේ පික්සෙල් ඒවායේ සුචිගත කරන ලද පික්සෙල් සඳහා පලත් රූපයේ හුවමාරු කර ගමනාන්ත රූපය ලියමි.

රූප ගොනු කියවීමට / ලිවීමට මම FreeImage පුස්තකාලය භාවිතා කරමි.

කේතය

/* Inputs: 2 image files of same area
Outputs: image1 made from pixels of image2*/
#include <iostream>
#include <stdlib.h>
#include "FreeImage.h"
#include <vector>
#include <algorithm>

class pixel
{
public:
    int x, y;
    BYTE r, g, b;
    float val;  //color value; weighted 'brightness'
};

bool sortByColorVal(const pixel &lhs, const pixel &rhs) { return lhs.val > rhs.val; }

FIBITMAP* GenericLoader(const char* lpszPathName, int flag) 
{
    FREE_IMAGE_FORMAT fif = FIF_UNKNOWN;

    // check the file signature and deduce its format
    // (the second argument is currently not used by FreeImage)
    fif = FreeImage_GetFileType(lpszPathName, 0);
    if (fif == FIF_UNKNOWN) 
    {
        // no signature ?
        // try to guess the file format from the file extension
        fif = FreeImage_GetFIFFromFilename(lpszPathName);
    }
    // check that the plugin has reading capabilities ...
    if ((fif != FIF_UNKNOWN) && FreeImage_FIFSupportsReading(fif)) 
    {
        // ok, let's load the file
        FIBITMAP *dib = FreeImage_Load(fif, lpszPathName, flag);
        // unless a bad file format, we are done !
        return dib;
    }
    return NULL;
}

bool GenericWriter(FIBITMAP* dib, const char* lpszPathName, int flag) 
{
    FREE_IMAGE_FORMAT fif = FIF_UNKNOWN;
    BOOL bSuccess = FALSE;

    if (dib) 
    {
        // try to guess the file format from the file extension
        fif = FreeImage_GetFIFFromFilename(lpszPathName);
        if (fif != FIF_UNKNOWN) 
        {
            // check that the plugin has sufficient writing and export capabilities ...
            WORD bpp = FreeImage_GetBPP(dib);
            if (FreeImage_FIFSupportsWriting(fif) && FreeImage_FIFSupportsExportBPP(fif, bpp)) 
            {
                // ok, we can save the file
                bSuccess = FreeImage_Save(fif, dib, lpszPathName, flag);
                // unless an abnormal bug, we are done !
            }
        }
    }
    return (bSuccess == TRUE) ? true : false;
}

void FreeImageErrorHandler(FREE_IMAGE_FORMAT fif, const char *message) 
{
    std::cout << std::endl << "*** ";
    if (fif != FIF_UNKNOWN) 
    {
        std::cout << "ERROR: " << FreeImage_GetFormatFromFIF(fif) << " Format" << std::endl;
    }
    std::cout << message;
    std::cout << " ***" << std::endl;
}

FIBITMAP* Convert24BPP(FIBITMAP* dib)
{
    if (FreeImage_GetBPP(dib) == 24) return dib;

    FIBITMAP *dib2 = FreeImage_ConvertTo24Bits(dib);
    FreeImage_Unload(dib);
    return dib2;
}
// ----------------------------------------------------------

int main(int argc, char **argv)
{
    // call this ONLY when linking with FreeImage as a static library
#ifdef FREEIMAGE_LIB
    FreeImage_Initialise();
#endif

    FIBITMAP *src = NULL, *pal = NULL;
    int result = EXIT_FAILURE;

    // initialize my own FreeImage error handler
    FreeImage_SetOutputMessage(FreeImageErrorHandler);

    // print version
    std::cout << "FreeImage version : " << FreeImage_GetVersion() << std::endl;

    if (argc != 4) 
    {
        std::cout << "USAGE : Pic2Pic <source image> <palette image> <output file name>" << std::endl;
        return EXIT_FAILURE;
    }

    // Load the src image
    src = GenericLoader(argv[1], 0);
    if (src) 
    {
        // load the palette image
        pal = GenericLoader(argv[2], 0);

        if (pal) 
        {
            //compare areas
            // if(!samearea) return EXIT_FAILURE;
            unsigned int width_src = FreeImage_GetWidth(src);
            unsigned int height_src = FreeImage_GetHeight(src);
            unsigned int width_pal = FreeImage_GetWidth(pal);
            unsigned int height_pal = FreeImage_GetHeight(pal);

            if (width_src * height_src != width_pal * height_pal)
            {
                std::cout << "ERROR: source and palette images do not have the same pixel area." << std::endl;
                result = EXIT_FAILURE;
            }
            else
            {
                //go to work!

                //first make sure everything is 24 bit:
                src = Convert24BPP(src);
                pal = Convert24BPP(pal);

                //retrieve the image data
                BYTE *bits_src = FreeImage_GetBits(src);
                BYTE *bits_pal = FreeImage_GetBits(pal);

                //make destination image
                FIBITMAP *dst = FreeImage_ConvertTo24Bits(src);
                BYTE *bits_dst = FreeImage_GetBits(dst);

                //make a vector of all the src pixels that we can sort by color value
                std::vector<pixel> src_pixels;
                for (unsigned int y = 0; y < height_src; ++y)
                {
                    for (unsigned int x = 0; x < width_src; ++x)
                    {
                        pixel p;
                        p.x = x;
                        p.y = y;

                        p.b = bits_src[y*width_src * 3 + x * 3];
                        p.g = bits_src[y*width_src * 3 + x * 3 + 1];
                        p.r = bits_src[y*width_src * 3 + x * 3 + 2];

                        //calculate color value using a weighted brightness for each channel
                        //p.val = 0.2126f * p.r + 0.7152f * p.g + 0.0722f * p.b; //from http://www.poynton.com/notes/colour_and_gamma/ColorFAQ.html
                        p.val = 0.5f * p.r + p.g + 0.1f * p.b;                      

                        src_pixels.push_back(p);
                    }
                }

                //sort by color value
                std::sort(src_pixels.begin(), src_pixels.end(), sortByColorVal);

                //make a vector of all palette pixels we can use
                std::vector<pixel> pal_pixels;

                for (unsigned int y = 0; y < height_pal; ++y)
                {
                    for (unsigned int x = 0; x < width_pal; ++x)
                    {
                        pixel p;

                        p.b = bits_pal[y*width_pal * 3 + x * 3];
                        p.g = bits_pal[y*width_pal * 3 + x * 3 + 1];
                        p.r = bits_pal[y*width_pal * 3 + x * 3 + 2];

                        p.val = 0.5f * p.r + p.g + 0.1f * p.b;

                        pal_pixels.push_back(p);
                    }
                }

                //sort by color value
                std::sort(pal_pixels.begin(), pal_pixels.end(), sortByColorVal);

                //for each src pixel, match it with same index palette pixel and copy to destination
                for (unsigned int i = 0; i < width_src * height_src; ++i)
                {
                    bits_dst[src_pixels[i].y * width_src * 3 + src_pixels[i].x * 3] = pal_pixels[i].b;
                    bits_dst[src_pixels[i].y * width_src * 3 + src_pixels[i].x * 3 + 1] = pal_pixels[i].g;
                    bits_dst[src_pixels[i].y * width_src * 3 + src_pixels[i].x * 3 + 2] = pal_pixels[i].r;
                }

                // Save the destination image
                bool bSuccess = GenericWriter(dst, argv[3], 0);
                if (!bSuccess)
                {
                    std::cout << "ERROR: unable to save " << argv[3] << std::endl;
                    std::cout << "This format does not support 24-bit images" << std::endl;
                    result = EXIT_FAILURE;
                }
                else result = EXIT_SUCCESS;

                FreeImage_Unload(dst);
            }

            // Free pal
            FreeImage_Unload(pal);
        }

        // Free src
        FreeImage_Unload(src);
    }

#ifdef FREEIMAGE_LIB
    FreeImage_DeInitialise();
#endif

    if (result == EXIT_SUCCESS) std::cout << "SUCCESS!" << std::endl;
    else std::cout << "FAILURE!" << std::endl;
    return result;
}

ප්රතිපල

ඇමරිකානු ගොතික් මොනා ලිසා පලත් භාවිතා කරයි ඇමරිකානු ගොතික් මොනා ලිසා පැලට් රේන්බෝ පලත් භාවිතා කරන ඇමරිකානු ගොතික් භාවිතා කරමින් ඇමරිකානු ගොතික් රේන්බෝ පැලේට් Scream palette භාවිතා කරමින් මොනා ලීසා මොනා ලිසා ස්ක්‍රීම් පැලට් මොනා ලීසා රේන්බෝ පලත් භාවිතා කරයි භාවිතා කරමින් මොනා ලිසා රේන්බෝ පැලට් තරු රාත්‍රී පලත් භාවිතා කර කෑගසන්න ස්ක්‍රීම් ස්ටාර්රි නයිට් පැලේට් භාවිතා කරයි


4

සී #

ලකුණු ඇණවුම් කර ඇත්තේ අහඹු ලෙස ඇවිදීමෙනි. සෑම විටම පලත් රූපයේ ආසන්නතම වර්ණය ලබා ගන්න. ඉතින් අන්තිම පික්සල් තරමක් නරකයි.

ප්රතිපල

ගොතික් පලට්

රූප විස්තරය මෙහි ඇතුළත් කරන්න

රූප විස්තරය මෙහි ඇතුළත් කරන්න

සහ ඇමරිකානු යුවළ විකිපීඩියාවෙන් පැමිණෙන අමුත්තන්

රූප විස්තරය මෙහි ඇතුළත් කරන්න

මොනා පැලට්

රූප විස්තරය මෙහි ඇතුළත් කරන්න

රූප විස්තරය මෙහි ඇතුළත් කරන්න

රූප විස්තරය මෙහි ඇතුළත් කරන්න

කේතය:

හේතුව මම නොදනිමි නමුත් කේතය ඉතා මන්දගාමී වේ ...

public class PixelExchanger
{
    public class ProgressInfo
    {
        public readonly Pixel NewPixel;
        public readonly int Percentage;

        public ProgressInfo(Pixel newPixel, int percentage)
        {
            this.NewPixel = newPixel;
            this.Percentage = percentage;
        }
    }

    public class Pixel
    {
        public readonly int X;
        public readonly int Y;
        public readonly Color Color;

        public Pixel(int x, int y, Color color)
        {
            this.X = x;
            this.Y = y;
            this.Color = color;
        }
    }

    private static Random r = new Random(0);

    private readonly Bitmap Pallete;
    private readonly Bitmap Image;

    private readonly int Width;
    private readonly int Height;

    private readonly Action<ProgressInfo> ProgressCallback;
    private System.Drawing.Image image1;
    private System.Drawing.Image image2;

    private int Area { get { return Width * Height; } }

    public PixelExchanger(Bitmap pallete, Bitmap image, Action<ProgressInfo> progressCallback = null)
    {
        this.Pallete = pallete;
        this.Image = image;

        this.ProgressCallback = progressCallback;

        Width = image.Width;
        Height = image.Height;

        if (Area != pallete.Width * pallete.Height)
            throw new ArgumentException("Image and Pallete have different areas!");
    }

    public Bitmap DoWork()
    {
        var array = GetColorArray();
        var map = GetColorMap(Image);
        var newMap = Go(array, map);

        var bm = new Bitmap(map.Length, map[0].Length);

        for (int i = 0; i < Width; i++)
        {
            for (int j = 0; j < Height; j++)
            {
                bm.SetPixel(i, j, newMap[i][j]);
            }
        }

        return bm;
    }

    public Color[][] Go(List<Color> array, Color[][] map)
    {
        var centralPoint = new Point(Width / 2, Height / 2);

        var q = OrderRandomWalking(centralPoint).ToArray();

        Color[][] newMap = new Color[map.Length][];
        for (int i = 0; i < map.Length; i++)
        {
            newMap[i] = new Color[map[i].Length];
        }

        double pointsDone = 0;

        foreach (var p in q)
        {
            newMap[p.X][p.Y] = Closest(array, map[p.X][p.Y]);

            pointsDone++;

            if (ProgressCallback != null)
            {
                var percent = 100 * (pointsDone / (double)Area);

                var progressInfo = new ProgressInfo(new Pixel(p.X, p.Y, newMap[p.X][p.Y]), (int)percent);

                ProgressCallback(progressInfo);
            }
        }

        return newMap;
    }

    private int[][] GetCardinals()
    {
        int[] nn = new int[] { -1, +0 };
        // int[] ne = new int[] { -1, +1 };
        int[] ee = new int[] { +0, +1 };
        // int[] se = new int[] { +1, +1 };
        int[] ss = new int[] { +1, +0 };
        // int[] sw = new int[] { +1, -1 };
        int[] ww = new int[] { +0, -1 };
        // int[] nw = new int[] { -1, -1 };

        var dirs = new List<int[]>();

        dirs.Add(nn);
        // dirs.Add(ne);
        dirs.Add(ee);
        // dirs.Add(se);
        dirs.Add(ss);
        // dirs.Add(sw);
        dirs.Add(ww);
        // dirs.Add(nw);

        return dirs.ToArray();
    }

    private Color Closest(List<Color> array, Color c)
    {
        int closestIndex = -1;

        int bestD = int.MaxValue;

        int[] ds = new int[array.Count];
        Parallel.For(0, array.Count, (i, state) =>
        {
            ds[i] = Distance(array[i], c);

            if (ds[i] <= 50)
            {
                closestIndex = i;
                state.Break();
            }
            else if (bestD > ds[i])
            {
                bestD = ds[i];
                closestIndex = i;
            }
        });

        var closestColor = array[closestIndex];

        array.RemoveAt(closestIndex);

        return closestColor;
    }

    private int Distance(Color c1, Color c2)
    {
        var r = Math.Abs(c1.R - c2.R);
        var g = Math.Abs(c1.G - c2.G);
        var b = Math.Abs(c1.B - c2.B);
        var s = Math.Abs(c1.GetSaturation() - c1.GetSaturation());

        return (int)s + r + g + b;
    }

    private HashSet<Point> OrderRandomWalking(Point p)
    {
        var points = new HashSet<Point>();

        var dirs = GetCardinals();
        var dir = new int[] { 0, 0 };

        while (points.Count < Width * Height)
        {
            bool inWidthBound = p.X + dir[0] < Width && p.X + dir[0] >= 0;
            bool inHeightBound = p.Y + dir[1] < Height && p.Y + dir[1] >= 0;

            if (inWidthBound && inHeightBound)
            {
                p.X += dir[0];
                p.Y += dir[1];

                points.Add(p);
            }

            dir = dirs.Random(r);
        }

        return points;
    }

    private static Color[][] GetColorMap(Bitmap b1)
    {
        int hight = b1.Height;
        int width = b1.Width;

        Color[][] colorMatrix = new Color[width][];
        for (int i = 0; i < width; i++)
        {
            colorMatrix[i] = new Color[hight];
            for (int j = 0; j < hight; j++)
            {
                colorMatrix[i][j] = b1.GetPixel(i, j);
            }
        }
        return colorMatrix;
    }

    private List<Color> GetColorArray()
    {
        var map = GetColorMap(Pallete);

        List<Color> colors = new List<Color>();

        foreach (var line in map)
        {
            colors.AddRange(line);
        }

        return colors;
    }
}

2
මේවා නම් නියමයි. ඒවා පිළිස්සී හෝ කුණු වීමට කොහේ හරි දමා ඇති ඡායාරූප මෙන් පෙනේ.

ස්තූතියි, A ඇල්ගොරිතම කිහිපයක් කළා, නමුත් අනෙක් පිළිතුරු අනෙක් පිළිතුරු වලට බොහෝ සෙයින් සමානයි. ඒ නිසා මම වඩාත් සුවිශේෂී
RMalke

3

සී #

වර්ණ සංසන්දනය කරන්නේ ඒවා කොතරම් දුරින්ද යන්නයි. මධ්යයේ සිට ආරම්භ වේ.

සංස්කරණය කරන්න: යාවත්කාලීන කරන ලදි, දැන් 1.5x පමණ වේගවත් විය යුතුය.

ඇමරිකානු ගොතික්
රූප විස්තරය මෙහි ඇතුළත් කරන්න
ද ස්ක්‍රීම්
රූප විස්තරය මෙහි ඇතුළත් කරන්න
ස්ටාර්රි නයිට්
රූප විස්තරය මෙහි ඇතුළත් කරන්න
මාර්බල්ස්
රූප විස්තරය මෙහි ඇතුළත් කරන්න
ගඟ
රූප විස්තරය මෙහි ඇතුළත් කරන්න
ද මෙහි කහ චෙවි:
රූප විස්තරය මෙහි ඇතුළත් කරන්න

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Threading.Tasks;
using System.Diagnostics;

namespace ConsoleApplication1
{
    class Pixel
    {
        public int X = 0;
        public int Y = 0;
        public Color Color = new Color();
        public Pixel(int x, int y, Color clr)
        {
            Color = clr;
            X = x;
            Y = y;
        }
        public Pixel()
        {
        }
    }
    class Vector2
    {
        public int X = 0;
        public int Y = 0;
        public Vector2(int x, int y)
        {
            X = x;
            Y = y;
        }
        public Vector2()
        {
        }
        public double Diagonal()
        {
            return Math.Sqrt((X * X) + (Y * Y));
        }
    }
    class ColorCollection
    {
        Dictionary<Color, int> dict = new Dictionary<Color, int>();
        public ColorCollection()
        {
        }
        public void AddColor(Color color)
        {
            if (dict.ContainsKey(color))
            {
                dict[color]++;
                return;
            }
            dict.Add(color, 1);
        }
        public void UseColor(Color color)
        {
            if (dict.ContainsKey(color))
                dict[color]--;
            if (dict[color] < 1)
                dict.Remove(color);
        }
        public Color FindBestColor(Color color)
        {
            Color ret = dict.First().Key;
            int p = this.CalculateDifference(ret, color);
            foreach (KeyValuePair<Color, int> pair in dict)
            {
                int points = CalculateDifference(pair.Key, color);
                if (points < p)
                {
                    ret = pair.Key;
                    p = points;
                }
            }
            this.UseColor(ret);
            return ret;
        }
        int CalculateDifference(Color c1, Color c2)
        {
            int ret = 0;
            ret = ret + Math.Abs(c1.R - c2.R);
            ret = ret + Math.Abs(c1.G - c2.G);
            ret = ret + Math.Abs(c1.B - c2.B);
            return ret;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            string img1 = "";
            string img2 = "";
            if (args.Length != 2)
            {
                Console.Write("Where is the first picture located? ");
                img1 = Console.ReadLine();
                Console.Write("Where is the second picture located? ");
                img2 = Console.ReadLine();
            }
            else
            {
                img1 = args[0];
                img2 = args[1];
            }
            Bitmap bmp1 = new Bitmap(img1);
            Bitmap bmp2 = new Bitmap(img2);
            Console.WriteLine("Getting colors....");
            ColorCollection colors = GetColors(bmp1);
            Console.WriteLine("Getting pixels....");
            List<Pixel> pixels = GetPixels(bmp2);
            int centerX = bmp2.Width / 2;
            int centerY = bmp2.Height / 2;
            pixels.Sort((p1, p2) =>
            {
                Vector2 p1_v = new Vector2(Math.Abs(p1.X - centerX), Math.Abs(p1.Y - centerY));
                Vector2 p2_v = new Vector2(Math.Abs(p2.X - centerX), Math.Abs(p2.Y - centerY));
                double d1 = p1_v.Diagonal();
                double d2 = p2_v.Diagonal();
                if (d1 > d2)
                    return 1;
                else if (d1 == d2)
                    return 0;
                return -1;
            });
            Console.WriteLine("Calculating...");
            int k = 0;
            Stopwatch sw = Stopwatch.StartNew();
            for (int i = 0; i < pixels.Count; i++)
            {
                if (i % 100 == 0 && i != 0)
                {
                    float percentage = ((float)i / (float)pixels.Count) * 100;
                    Console.WriteLine(percentage.ToString("0.00") + "% completed(" + i + "/" + pixels.Count + ")");
                    Console.SetCursorPosition(0, Console.CursorTop - 1);
                }
                Color set = colors.FindBestColor(pixels[i].Color);
                pixels[i].Color = set;
                k++;
            }
            sw.Stop();
            Console.WriteLine("Saving...");
            Bitmap result = WritePixelsToBitmap(pixels, bmp2.Width, bmp2.Height);
            result.Save(img1 + ".png");
            Console.WriteLine("Completed in " + sw.Elapsed.TotalSeconds + " seconds. Press a key to exit.");
            Console.ReadKey();
        }
        static Bitmap WritePixelsToBitmap(List<Pixel> pixels, int width, int height)
        {
            Bitmap bmp = new Bitmap(width, height);
            foreach (Pixel pixel in pixels)
            {
                bmp.SetPixel(pixel.X, pixel.Y, pixel.Color);
            }
            return bmp;
        }

        static ColorCollection GetColors(Bitmap bmp)
        {
            ColorCollection ret = new ColorCollection();
            for (int x = 0; x < bmp.Width; x++)
            {
                for (int y = 0; y < bmp.Height; y++)
                {
                    Color clr = bmp.GetPixel(x, y);
                    ret.AddColor(clr);
                }
            }
            return ret;
        }
        static List<Pixel> GetPixels(Bitmap bmp)
        {
            List<Pixel> ret = new List<Pixel>();
            for (int x = 0; x < bmp.Width; x++)
            {
                for (int y = 0; y < bmp.Height; y++)
                {
                    Color clr = bmp.GetPixel(x, y);
                    ret.Add(new Pixel(x, y, clr));
                }
            }
            return ret;
        }
    }
}

3

මගේ අනෙක් පිළිතුර ලෙස ඉතා සමාන ඇල්ගොරිතමයක් භාවිතා කිරීමට උත්සාහ කිරීමට මම තීරණය කළෙමි, නමුත් තනි පික්සෙල් වෙනුවට පික්සල් 2x2 කොටස් මාරු කිරීම පමණි. අවාසනාවකට මෙන්, මෙම ඇල්ගොරිතමය මඟින් රූපයේ මානයන් 2 න් බෙදිය යුතු බවට අමතර බාධාවක් එක් කරයි, එමඟින් මා ප්‍රමාණ වෙනස් නොකරන්නේ නම් කිරණ ගෝල භාවිතා කළ නොහැක.

සමහර ප්‍රති results ල වලට මම ඇත්තටම කැමතියි!

ගංගා පලත් සහිත ඇමරිකානු ගොතික්:

රූප විස්තරය මෙහි ඇතුළත් කරන්න

ඇමරිකානු ගොතික් පලත් සමඟ මොනා ලීසා:

රූප විස්තරය මෙහි ඇතුළත් කරන්න

ගංගා තලය සහිත මොනා ලීසා:

රූප විස්තරය මෙහි ඇතුළත් කරන්න

මම 4x4 ද උත්සාහ කළෙමි, මෙන්න මගේ ප්‍රියතමයන්!

කෑගැසීමේ පලත් සමඟ තරු රාත්‍රිය:

රූප විස්තරය මෙහි ඇතුළත් කරන්න

ඇමරිකානු ගොතික් පලත් සමඟ මොනා ලීසා:

රූප විස්තරය මෙහි ඇතුළත් කරන්න

මොනා ලිසා පලත් සමඟ ඇති කෑගැසීම:

රූප විස්තරය මෙහි ඇතුළත් කරන්න

මොනා ලිසා පලත් සමඟ ඇමරිකානු ගොතික්:

රූප විස්තරය මෙහි ඇතුළත් කරන්න


1
එකම දේ කිරීම ගැන සිතමින් සිටියේය + වර්ග කුට්ටි මත පදනම්ව පික්සල් බර ගණනය කරන්න. මම මොනා ලිසා ප්‍රති results ල වලට බෙහෙවින් කැමතියි - ඒවා රූපයේ රූපයෙන් මට මතක් කර දෙයි. ඔබට අහම්බෙන් 4x4 කුට්ටි කළ හැකිද?
eithed

1
iteethedog මම 4x4 අත්හදා බැලුවෙමි. මගේ යාවත්කාලීන කළ පිළිතුර බලන්න!
LVBen

3

සී #

මෙය සැබවින්ම සැබවින්ම මන්දගාමී ය, නමුත් එය විශාල කාර්යයක් කරයි, විශේෂයෙන් කිරණ සහිත ගෝලාකාර තලය භාවිතා කරන විට.

රූප විස්තරය මෙහි ඇතුළත් කරන්න රූප විස්තරය මෙහි ඇතුළත් කරන්න රූප විස්තරය මෙහි ඇතුළත් කරන්න රූප විස්තරය මෙහි ඇතුළත් කරන්න රූප විස්තරය මෙහි ඇතුළත් කරන්න

කෑගැසීමේ පලත්:

රූප විස්තරය මෙහි ඇතුළත් කරන්න රූප විස්තරය මෙහි ඇතුළත් කරන්න

මොනා ලීසා පලත්:

රූප විස්තරය මෙහි ඇතුළත් කරන්න රූප විස්තරය මෙහි ඇතුළත් කරන්න රූප විස්තරය මෙහි ඇතුළත් කරන්න රූප විස්තරය මෙහි ඇතුළත් කරන්න

ඇමරිකානු ගොතික් පලත්:

රූප විස්තරය මෙහි ඇතුළත් කරන්න රූප විස්තරය මෙහි ඇතුළත් කරන්න

ගංගා තලය:

රූප විස්තරය මෙහි ඇතුළත් කරන්න රූප විස්තරය මෙහි ඇතුළත් කරන්න රූප විස්තරය මෙහි ඇතුළත් කරන්න

තරු රාත්‍රී පලත්:

රූප විස්තරය මෙහි ඇතුළත් කරන්න රූප විස්තරය මෙහි ඇතුළත් කරන්න

   class Program
   {
      class Pixel
      {
         public int x;
         public int y;
         public Color color;
         public Pixel(int x, int y, Color color)
         {
            this.x = x;
            this.y = y;
            this.color = color;
         }
      }

      static Pixel BaselineColor = new Pixel(0, 0, Color.FromArgb(0, 0, 0, 0));

      static void Main(string[] args)
      {
         string sourceDirectory = "pic" + args[0] + ".png";
         string paletteDirectory = "pic" + args[1] + ".png";

         using (Bitmap source = Bitmap.FromFile(sourceDirectory) as Bitmap)
         {
            List<Pixel> sourcePixels = GetPixels(source).ToList();
            LinkedList<Pixel> palettePixels;

            using (Bitmap palette = Bitmap.FromFile(paletteDirectory) as Bitmap)
            {
               palettePixels = GetPixels(palette) as LinkedList<Pixel>;
            }

            if (palettePixels.Count != sourcePixels.Count)
            {
               throw new Exception("OH NO!!!!!!!!");
            }

            sourcePixels.Sort((x, y) => GetDiff(y, BaselineColor) - GetDiff(x, BaselineColor));

            LinkedList<Pixel> newPixels = new LinkedList<Pixel>();
            foreach (Pixel p in sourcePixels)
            {
               Pixel newPixel = GetClosestColor(palettePixels, p);
               newPixels.AddLast(newPixel);
            }

            foreach (var p in newPixels)
            {
               source.SetPixel(p.x, p.y, p.color);
            }
            source.Save("Out" + args[0] + "to" + args[1] + ".png");
         }
      }

      private static IEnumerable<Pixel> GetPixels(Bitmap source)
      {
         List<Pixel> newList = new List<Pixel>();
         for (int x = 0; x < source.Width; x++)
         {
            for (int y = 0; y < source.Height; y++)
            {
               newList.Add(new Pixel(x, y, source.GetPixel(x, y)));
            }
         }
         return newList;
      }

      private static Pixel GetClosestColor(LinkedList<Pixel> palettePixels, Pixel p)
      {
         Pixel minPixel = palettePixels.First();
         int diff = GetDiff(minPixel, p);
         foreach (var pix in palettePixels)
         {
            int current = GetDiff(pix, p);
            if (current < diff)
            {
               diff = current;
               minPixel = pix;
               if (diff == 0)
               {
                  return minPixel;
               }
            }
         }
         palettePixels.Remove(minPixel);
         return new Pixel(p.x, p.y, minPixel.color);
      }

      private static int GetDiff(Pixel a, Pixel p)
      {
         return GetProx(a.color, p.color);
      }

      private static int GetProx(Color a, Color p)
      {
         int red = (a.R - p.R) * (a.R - p.R);
         int green = (a.G - p.G) * (a.G - p.G);
         int blue = (a.B - p.B) * (a.B - p.B);
         return red + blue + green;
      }
   }

3

ජාවා - තවත් සිතියම්කරණ ප්‍රවේශයක්

සංස්කරණය 1: එය G + හි “ගණිත” පරිසරයක බෙදාගැනීමෙන් පසුව, අප සියල්ලන්ම සංකීර්ණතාවයන් මඟහරවා ගැනීම සඳහා විවිධ ක්‍රම සමඟ ගැලපෙන ප්‍රවේශයන් භාවිතා කරන බව පෙනේ.

සංස්කරණය 2: මම මගේ ගූගල් ඩ්‍රයිව්හි පින්තූර අවුල් කර නැවත ආරම්භ කළෙමි, එබැවින් පැරණි සබැඳි තවදුරටත් ක්‍රියා නොකරයි. කණගාටුයි, මම තව තවත් සබැඳි සඳහා වැඩි කීර්තියක් ලබා ගනිමින් සිටිමි.

සංස්කරණය 3: අනෙක් ලිපි කියවීමෙන් මට යම් ආශ්වාදයක් ලැබුණි. ඉලක්කගත රූපයේ පිහිටීම අනුව යම් යම් වෙනස්කම් කිරීමට මම දැන් ක්‍රමලේඛය වේගවත් කර CPU කාලය නැවත ආයෝජනය කළෙමි.

සංස්කරණය 4: නව වැඩසටහන් අනුවාදය. ඉක්මනින්! තියුණු කොන් සහ ඉතා සුමට වෙනස්කම් සහිත ප්‍රදේශ දෙකටම විශේෂ ප්‍රතිකාර කිරීම (කිරණ සොයා ගැනීමට බොහෝ සෙයින් උපකාරී වේ, නමුත් මොනා ලිසාට ඉඳහිට රතු ඇස් ලබා දෙයි)! සජීවිකරණ වලින් අතරමැදි රාමු ජනනය කිරීමේ හැකියාව!

මම ඇත්තටම අදහසට ඇලුම් කළ අතර ක්වින්කන්ක්ස් විසඳුම මා තුළ කුතුහලයක් ඇති කළේය. ඒ නිසා මම හිතුවා මට මගේ යුරෝ ශත 2 එකතු කරන්න පුළුවන් වෙයි කියලා.

අදහස නම්, අපට පැහැදිලිවම වර්ණාලේප දෙකක් අතර (කෙසේ හෝ සමීප) සිතියමක් අවශ්‍ය බවය.

මෙම අදහස සමඟ මම පළමු රාත්‍රිය ගත කළේ ස්ථාවර විවාහ ඇල්ගොරිතමයක් වේගයෙන් ධාවනය කිරීමට සහ මගේ පරිගණකයේ මතකය සමඟ අපේක්ෂකයින් 123520 ක් සඳහා ය. මම මතක පරාසයට ඇතුළු වන විට, ධාවන කාල ගැටළුව විසඳිය නොහැකි බව මට පෙනී ගියේය.

දෙවන රාත්‍රියේදී මම තව දුරටත් හංගේරියානු ඇල්ගොරිතමයට කිමිදීමට තීරණය කළෙමි, එය ආසන්න වශයෙන් ගුණාංග ලබා දීමට පොරොන්දු විය, එනම් රූපයේ වර්ණ අතර අවම දුර. වාසනාවකට මෙන්, ජාවා ක්‍රියාත්මක කිරීම සඳහා 3 ක් සූදානම් බව මට පෙනී ගියේය (ප්‍රාථමික ඇල්ගොරිතම සඳහා ගූගල් කිරීම දුෂ්කර වන බොහෝ අර්ධ නිමි ශිෂ්‍ය පැවරුම් ගණන් නොගනී). නමුත් යමෙකු අපේක්ෂා කළ පරිදි, ධාවන කාලය සහ මතක භාවිතය අනුව හංගේරියානු ඇල්ගොරිතම ඊටත් වඩා නරක ය. ඊටත් වඩා භයානක දෙය නම්, මා විසින් පරීක්‍ෂා කරන ලද ක්‍රියාත්මක කිරීම් 3 ම ඉඳහිට වැරදි ප්‍රති .ල ලබා දීමයි. මේවා මත පදනම් විය හැකි වෙනත් වැඩසටහන් ගැන සිතන විට මම වෙවුලමි.

තෙවන ප්‍රවේශය (දෙවන රාත්‍රියේ අවසානය) පහසු, ඉක්මන්, වේගවත් හා සියල්ලටම පසු එතරම් නරක නැත: රූප දෙකෙහිම දීප්තිය හා සරල සිතියම ශ්‍රේණිගත කිරීමෙන් වර්ග කරන්න, එනම් අඳුරු සිට අඳුරු, දෙවන අඳුරු සිට දෙවන අඳුරු. මෙය වහාම අහඹු ලෙස ඉසින තියුණු පෙනුමක් ඇති කළු සහ සුදු ප්‍රතිනිර්මාණයක් ඇති කරයි.

* ප්‍රවේශය 4 සහ අවසාන (දෙවන රාත්‍රියේ උදේ) ඉහත දීප්තිමත්ව සිතියම්ගත කිරීම සමඟ ආරම්භ වන අතර විවිධ පික්සල් අනුක්‍රමික අනුපිළිවෙලට හංගේරියානු ඇල්ගොරිතම යෙදීමෙන් දේශීය නිවැරදි කිරීම් එක් කරයි. මේ ආකාරයෙන් මම වඩා හොඳ සිතියම් ගත කර ඇති අතර ගැටලුවේ සංකීර්ණත්වය සහ ක්‍රියාත්මක කිරීමේදී ඇති වන දෝෂ යන දෙකම වටා වැඩ කළෙමි.

ඉතින් මෙන්න සමහර ජාවා කේත, සමහර කොටස් මෙහි පළ කර ඇති අනෙකුත් ජාවා කේත වලට සමාන විය හැකිය. භාවිතා කරන ලද කුසගින්න යනු මුලින් ඔන්ටෝලොජි සිමිලරි ව්‍යාපෘතියේ ජෝන් මිලර්ස්ගේ පැච් කරන ලද අනුවාදයකි. මෙය මා සොයාගත් වේගවත්ම ක්‍රමය වන අතර අඩුම දෝෂ පෙන්වයි.

import java.awt.image.BufferedImage;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Set;
import java.util.HashSet;
import java.util.Map;
import java.util.HashMap;
import java.util.List;
import javax.imageio.ImageIO;

/**
 *
 */
public class PixelRearranger {

    private final String mode;

    public PixelRearranger(String mode)
    {
        this.mode = mode;
    }

    public final static class Pixel {
        final BufferedImage img;
        final int val;
        final int r, g, b;
        final int x, y;

        public Pixel(BufferedImage img, int x, int y) {
            this.x = x;
            this.y = y;
            this.img = img;
            if ( img != null ) {
                val = img.getRGB(x,y);
                r = ((val & 0xFF0000) >> 16);
                g = ((val & 0x00FF00) >> 8);
                b = ((val & 0x0000FF));
            } else {
                val = r = g = b = 0;
            }
        }

        @Override
        public int hashCode() {
            return x + img.getWidth() * y + img.hashCode();
        }

        @Override
        public boolean equals(Object o) {
            if ( !(o instanceof Pixel) ) return false;
            Pixel p2 = (Pixel) o;
            return p2.x == x && p2.y == y && p2.img == img;
        }

        public double cd() {
            double x0 = 0.5 * (img.getWidth()-1);
            double y0 = 0.5 * (img.getHeight()-1);
            return Math.sqrt(Math.sqrt((x-x0)*(x-x0)/x0 + (y-y0)*(y-y0)/y0));
        }

        @Override
        public String toString() { return "P["+r+","+g+","+b+";"+x+":"+y+";"+img.getWidth()+":"+img.getHeight()+"]"; }
    }

    public final static class Pair
        implements Comparable<Pair>
    {   
        public Pixel palette, from;
        public double d;

        public Pair(Pixel palette, Pixel from)
        {
            this.palette = palette;
            this.from = from;
            this.d = distance(palette, from);
        }

        @Override
        public int compareTo(Pair e2)
        {
            return sgn(e2.d - d);
        }

        @Override
        public String toString() { return "E["+palette+from+";"+d+"]"; }
    }

    public static int sgn(double d) { return d > 0.0 ? +1 : d < 0.0 ? -1 : 0; }

    public final static int distance(Pixel p, Pixel q)
    {
        return 3*(p.r-q.r)*(p.r-q.r) + 6*(p.g-q.g)*(p.g-q.g) + (p.b-q.b)*(p.b-q.b);
    }

    public final static Comparator<Pixel> LUMOSITY_COMP = (p1,p2) -> 3*(p1.r-p2.r)+6*(p1.g-p2.g)+(p1.b-p2.b);


    public final static class ArrangementResult
    {
        private List<Pair> pairs;

        public ArrangementResult(List<Pair> pairs)
        {
            this.pairs = pairs;
        }

        /** Provide the output image */
        public BufferedImage finalImage()
        {
            BufferedImage target = pairs.get(0).from.img;
            BufferedImage res = new BufferedImage(target.getWidth(),
                target.getHeight(), BufferedImage.TYPE_INT_RGB);
            for(Pair p : pairs) {
                Pixel left = p.from;
                Pixel right = p.palette;
                res.setRGB(left.x, left.y, right.val);
            }
            return res;
        }

        /** Provide an interpolated image. 0 le;= alpha le;= 1 */
        public BufferedImage interpolateImage(double alpha)
        {
            BufferedImage target = pairs.get(0).from.img;
            int wt = target.getWidth(), ht = target.getHeight();
            BufferedImage palette = pairs.get(0).palette.img;
            int wp = palette.getWidth(), hp = palette.getHeight();
            int w = Math.max(wt, wp), h = Math.max(ht, hp);
            BufferedImage res = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
            int x0t = (w-wt)/2, y0t = (h-ht)/2;
            int x0p = (w-wp)/2, y0p = (h-hp)/2;
            double a0 = (3.0 - 2.0*alpha)*alpha*alpha;
            double a1 = 1.0 - a0;
            for(Pair p : pairs) {
                Pixel left = p.from;
                Pixel right = p.palette;
                int x = (int) (a1 * (right.x + x0p) + a0 * (left.x + x0t));
                int y = (int) (a1 * (right.y + y0p) + a0 * (left.y + y0t));
                if ( x < 0 || x >= w ) System.out.println("x="+x+", w="+w+", alpha="+alpha);
                if ( y < 0 || y >= h ) System.out.println("y="+y+", h="+h+", alpha="+alpha);
                res.setRGB(x, y, right.val);
            }
            return res;
        }
    }

    public ArrangementResult rearrange(BufferedImage target, BufferedImage palette)
    {
        List<Pixel> targetPixels = getColors(target);
        int n = targetPixels.size();
        System.out.println("total Pixels "+n);
        Collections.sort(targetPixels, LUMOSITY_COMP);

        final double[][] energy = energy(target);

        List<Pixel> palettePixels = getColors(palette);
        Collections.sort(palettePixels, LUMOSITY_COMP);

        ArrayList<Pair> pairs = new ArrayList<>(n);
        for(int i = 0; i < n; i++) {
            Pixel pal = palettePixels.get(i);
            Pixel to = targetPixels.get(i);
            pairs.add(new Pair(pal, to));
        }
        correct(pairs, (p1,p2) -> sgn(p2.d*p2.from.b - p1.d*p1.from.b));
        correct(pairs, (p1,p2) -> sgn(p2.d*p2.from.r - p1.d*p1.from.r));
        // generates visible circular artifacts: correct(pairs, (p1,p2) -> sgn(p2.d*p2.from.cd() - p1.d*p1.from.cd()));
        correct(pairs, (p1,p2) -> sgn(energy[p2.from.x][p2.from.y]*p2.d - energy[p1.from.x][p1.from.y]*p1.d));
        correct(pairs, (p1,p2) -> sgn(p2.d/(1+energy[p2.from.x][p2.from.y]) - p1.d/(1+energy[p1.from.x][p1.from.y])));
        // correct(pairs, null);
        return new ArrangementResult(pairs);

    }

    /**
     * derive an energy map, to detect areas of lots of change.
     */
    public double[][] energy(BufferedImage img)
    {
        int n = img.getWidth();
        int m = img.getHeight();
        double[][] res = new double[n][m];
        for(int x = 0; x < n; x++) {
            for(int y = 0; y < m; y++) {
                int rgb0 = img.getRGB(x,y);
                int count = 0, sum = 0;
                if ( x > 0 ) {
                    count++; sum += dist(rgb0, img.getRGB(x-1,y));
                    if ( y > 0 ) { count++; sum += dist(rgb0, img.getRGB(x-1,y-1)); }
                    if ( y < m-1 ) { count++; sum += dist(rgb0, img.getRGB(x-1,y+1)); }
                }
                if ( x < n-1 ) {
                    count++; sum += dist(rgb0, img.getRGB(x+1,y));
                    if ( y > 0 ) { count++; sum += dist(rgb0, img.getRGB(x+1,y-1)); }
                    if ( y < m-1 ) { count++; sum += dist(rgb0, img.getRGB(x+1,y+1)); }
                }
                if ( y > 0 ) { count++; sum += dist(rgb0, img.getRGB(x,y-1)); }
                if ( y < m-1 ) { count++; sum += dist(rgb0, img.getRGB(x,y+1)); }
                res[x][y] = Math.sqrt((double)sum/count);
            }
        }
        return res;
    }

    public int dist(int rgb0, int rgb1) {
        int r0 = ((rgb0 & 0xFF0000) >> 16);
        int g0 = ((rgb0 & 0x00FF00) >> 8);
        int b0 = ((rgb0 & 0x0000FF));
        int r1 = ((rgb1 & 0xFF0000) >> 16);
        int g1 = ((rgb1 & 0x00FF00) >> 8);
        int b1 = ((rgb1 & 0x0000FF));
        return 3*(r0-r1)*(r0-r1) + 6*(g0-g1)*(g0-g1) + (b0-b1)*(b0-b1);
    }

    private void correct(ArrayList<Pair> pairs, Comparator<Pair> comp)
    {
        Collections.sort(pairs, comp);
        int n = pairs.size();
        int limit = Math.min(n, 133); // n / 1000;
        int limit2 = Math.max(1, n / 3 - limit);
        int step = (2*limit + 2)/3;
        for(int base = 0; base < limit2; base += step ) {
            List<Pixel> list1 = new ArrayList<>();
            List<Pixel> list2 = new ArrayList<>();
            for(int i = base; i < base+limit; i++) {
                list1.add(pairs.get(i).from);
                list2.add(pairs.get(i).palette);
            }
            Map<Pixel, Pixel> connection = rematch(list1, list2);
            int i = base;
            for(Pixel p : connection.keySet()) {
                pairs.set(i++, new Pair(p, connection.get(p)));
            }
        }
    }

    /**
     * Glue code to do an hungarian algorithm distance optimization.
     */
    public Map<Pixel,Pixel> rematch(List<Pixel> liste1, List<Pixel> liste2)
    {
        int n = liste1.size();
        double[][] cost = new double[n][n];
        Set<Pixel> s1 = new HashSet<>(n);
        Set<Pixel> s2 = new HashSet<>(n);
        for(int i = 0; i < n; i++) {
            Pixel ii = liste1.get(i);
            for(int j = 0; j < n; j++) {
                Pixel ij = liste2.get(j);
                cost[i][j] = -distance(ii,ij);
            }
        }
        Map<Pixel,Pixel> res = new HashMap<>();
        int[] resArray = Hungarian.hungarian(cost);
        for(int i = 0; i < resArray.length; i++) {
            Pixel ii = liste1.get(i);
            Pixel ij = liste2.get(resArray[i]);
            res.put(ij, ii);
        }
        return res;
    }

    public static List<Pixel> getColors(BufferedImage img) {
        int width = img.getWidth();
        int height = img.getHeight();
        List<Pixel> colors = new ArrayList<>(width * height);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                colors.add(new Pixel(img, x, y));
            }
        }
        return colors;
    }

    public static List<Integer> getSortedTrueColors(BufferedImage img) {
        int width = img.getWidth();
        int height = img.getHeight();
        List<Integer> colors = new ArrayList<>(width * height);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                colors.add(img.getRGB(x, y));
            }
        }
        Collections.sort(colors);
        return colors;
    }

    public static void main(String[] args) throws Exception {
        int i = 0;
        String mode = args[i++];
        PixelRearranger pr = new PixelRearranger(mode);
        String a1 = args[i++];
        File in1 = new File(a1);
        String a2 = args[i++];
        File in2 = new File(a2);
        File out = new File(args[i++]);
        //
        BufferedImage target = ImageIO.read(in1);
        BufferedImage palette = ImageIO.read(in2);
        long t0 = System.currentTimeMillis();
        ArrangementResult result = pr.rearrange(target, palette);
        BufferedImage resultImg = result.finalImage();
        long t1 = System.currentTimeMillis();
        System.out.println("took "+0.001*(t1-t0)+" s");
        ImageIO.write(resultImg, "png", out);
        // Check validity
        List<Integer> paletteColors = getSortedTrueColors(palette);
        List<Integer> resultColors = getSortedTrueColors(resultImg);
        System.out.println("validate="+paletteColors.equals(resultColors));
        // In Mode A we do some animation!
        if ( "A".equals(mode) ) {
            for(int j = 0; j <= 50; j++) {
                BufferedImage stepImg = result.interpolateImage(0.02 * j);
                File oa = new File(String.format("anim/%s-%s-%02d.png", a1, a2, j));
                ImageIO.write(stepImg, "png", oa);
            }
        }
    }
}

වර්තමාන ධාවන කාලය ඉහත රූප යුගලයට තත්පර 20 සිට 30 දක්වා වේ, නමුත් එය වේගයෙන් ඉදිරියට ගෙනයාමට හෝ එයින් මදක් වැඩි ගුණාත්මක බවක් ලබා ගැනීමට අවශ්‍ය තරම් වෙනස් කිරීම් තිබේ.

මගේ නවක කීර්තිනාමය එවැනි සබැඳි / රූප සඳහා ප්‍රමාණවත් නොවන බව පෙනේ, එබැවින් රූප සාම්පල සඳහා මගේ ගූගල් ඩ්‍රයිව් ෆෝල්ඩරයට පෙළ කෙටිමඟක් ඇත: http://goo.gl/qZHTao

මට පළමුව පෙන්වීමට අවශ්‍ය සාම්පල:

මිනිස්සු -> මොනා ලීසා http://goo.gl/mGvq9h

ක්‍රමලේඛය සියළුම ලක්ෂ්‍ය ඛණ්ඩාංක නිරීක්ෂණය කරයි, නමුත් මට දැන් වෙහෙස දැනී ඇති අතර දැනට සජීවිකරණ කිරීමට සැලසුම් නොකරමි. මම වැඩි කාලයක් ගත කිරීමට නම්, මට හංගේරියානු ඇල්ගොරිතමයක් කළ හැකිය, නැතහොත් මගේ වැඩසටහනේ දේශීය ප්‍රශස්තිකරණ කාලසටහන වෙනස් කළ හැකිය.

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.