遍历图片的像素,每n个像素范围画一个马赛克:圆形或矩形。
马赛克使用原像素的颜色值,也可以调亮或调暗。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 |
import java.awt.image.BufferedImage; import javax.swing.ImageIcon; import javax.swing.JCheckBox; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JSlider; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import org.opencv.core.Mat; import org.opencv.core.Point; import org.opencv.core.Scalar; import org.opencv.imgcodecs.Imgcodecs; import org.opencv.imgproc.Imgproc; public class PixelPic extends JFrame { private JLabel imageView; private Mat srcMat; public PixelPic() { JCheckBox pixelBtn = new JCheckBox("像素画"); pixelBtn.setBounds(10, 10, 90, 25); JSlider stepBar = new JSlider(1, 20); stepBar.setValue(5); stepBar.setBounds(110, 10, 150, 25); pixelBtn.addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { pixelPic(pixelBtn.isSelected(), stepBar.getValue()); } }); stepBar.addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { pixelPic(pixelBtn.isSelected(), stepBar.getValue()); } }); imageView = new JLabel(""); imageView.setBounds(0, 40, 512, 512); this.setTitle("像素画"); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setSize(550, 600); this.getContentPane().setLayout(null); this.getContentPane().add(pixelBtn); this.getContentPane().add(stepBar); this.getContentPane().add(imageView); srcMat = Imgcodecs.imread("./lena.jpg"); //, Imgcodecs.CV_LOAD_IMAGE_COLOR); setIcon(srcMat); } // 黑天照手电筒效果 private void pixelPic(boolean isPixel, int _step) { if (!isPixel) { setIcon(srcMat); return; } int step = _step; int radius = step / 2 + 1; int thickness = -1; Mat dstMat = new Mat(srcMat.rows(), srcMat.cols(), srcMat.type()); for (int y = 0; y < srcMat.rows(); y += step) { // 行,对应y轴 for (int x = 0; x < srcMat.cols(); x += step) { // 列,对应x轴 Point center = new Point(x, y); // 像素位置 double[] pixel = srcMat.get(y, x); // 像素,bgr double b = pixel[0]; double g = pixel[1]; double a = pixel[2]; drawCircle(dstMat, center, radius, b, g, a, thickness); } } setIcon(dstMat); } private void drawCircle(Mat canvas, Point center, int radius, double b, double g, double r, int thickness) { // 画圆 Imgproc.circle(canvas, // 画布 center, // 圆心 radius, // 半径 new Scalar(b, g, r), // 颜色 thickness); // 边框粗细。-1为填充 } private void setIcon(Mat mat) { BufferedImage image = CVUtil.matToBufferedImage(mat); // CVUtil 见 http://www.gaohaiyan.com/3229.html imageView.setIcon(new ImageIcon(image)); } } |
- end
声明
本文由崔维友 威格灵 cuiweiyou vigiles cuiweiyou 原创,转载请注明出处:http://www.gaohaiyan.com/3459.html
承接App定制、企业web站点、办公系统软件 设计开发,外包项目,毕设