0

对于一个课堂项目,我们需要一个实现 Sobel 算法的程序,并在多个线程中运行它作为练习,以熟悉线程。就线程而言,我的程序运行正常(据我所知),但是每当我使用超过 1 个线程实现它时,我会看到一个黑色边框在缓冲区似乎没有的分割区域上运行写入目标 BufferedImage。

以下是负责线程化和写入文件的方法的一些代码:

public void processImage(int threads)
{
    try{
        File imgFile = new File(bmpFile);
        image = ImageIO.read(imgFile);

        w = image.getWidth();
        wThr = (image.getWidth()/threads);
        h = image.getHeight();
        inData = new int[wThr*h];
        BufferedImage[] pieces = new BufferedImage[threads];

        //instantiate array used for storing pieces of image
        for (int i=0; i<threads; i++){
            pieces[i] = new BufferedImage(wThr, h, BufferedImage.TYPE_BYTE_GRAY);
        }

        wThr = pieces[0].getWidth();
        h = pieces[0].getHeight();

        //instantiate target image
        combined = new BufferedImage(w, h, BufferedImage.TYPE_BYTE_GRAY);

        //split into threads, each one taking a division of the image and running algorithm
        Thread[] threadList = new Thread[threads];
        for (int i = 0; i < threadList.length; i++) {
            image.getRaster().getPixels((i*wThr), 0, wThr, h, inData);  
            threadList[i] = new Pr1();
            threadList[i].start();
            try{
                threadList[i].join();
            }catch (InterruptedException ie) {}

            //Write images to pieces and draw pieces individually onto target image
            pieces[i].getRaster().setPixels(0, 0, wThr, h, outData);

            Graphics2D g = combined.createGraphics();
            g.drawImage(pieces[i], i*(wThr), 0, null);
            g.dispose();

        }
            outFile = new File("1.bmp");
            ImageIO.write(combined, "BMP", outFile);
    }
    catch(IOException e)
        {
        // Handle the exception here!
        }
    }

这是使用 2 个线程处理时的图像:http: //i.imgur.com/n5gasAW.png ?1

有人对如何修复此问题有任何见解吗?我已经以我能想到的各种方式更改了 BufferedImages 和数组的参数,但仍然没有运气。

4

0 回答 0