Converts the image being edited to grayscale
160605
public function toGrayscale()
    {
        $this->getInfo();

        $this->edited = imagecreate($this->width['orig'], $this->height['orig']);

        //Creates the 256 color palette
        for ($c=0;$c<256;$c++)

    {
            $palette[$c] = imagecolorallocate($this->edited,$c,$c,$c);
        }

        //Reads the origonal colors pixel by pixel
        for ($y=0;$y<$this->height['orig'];$y++)

    {
            for ($x=0;$x<$this->width['orig'];$x++)

    {
                $rgb = imagecolorat($this->original,$x,$y);
                $r = ($rgb >> 16) & 0xFF;
                $g = ($rgb >> 8) & 0xFF;
                $b = $rgb & 0xFF;

                //This is where we actually use yiq to modify our rbg values, and then convert them to our grayscale palette
                $gs = $this->colorToGray($r,$g,$b);
                imagesetpixel($this->edited,$x,$y,$palette[$gs]);
            }
        }

    }
1173597
def from_grayscale_and_depth(gray_im, depth_im):
        
        # check shape
        if gray_im.height != depth_im.height or gray_im.width != depth_im.width:
            raise ValueError(
                'Grayscale and depth images must have the same shape')

        # check frame
        if gray_im.frame != depth_im.frame:
            raise ValueError(
                'Grayscale and depth images must have the same frame')

        # form composite data
        gd_data = np.zeros([gray_im.height, gray_im.width, 2])
        gd_data[:, :, 0] = gray_im.data.astype(np.float64)
        gd_data[:, :, 1] = depth_im.data
        return GdImage(gd_data, frame=gray_im.frame)
277919
public static Bitmap grayToBitmap( GrayU8 input , Bitmap.Config config ) {
		Bitmap output = Bitmap.createBitmap(input.width, input.height, config);
		
		grayToBitmap(input,output,null);
		
		return output;
	}
293712
public Img gray() {
		final ColorConvertOp op = new ColorConvertOp(ColorSpace.getInstance(ColorSpace.CS_GRAY), null);
		this.targetImage = op.filter(getValidSrcImg(), null);
		return this;
	}
755746
public static <T extends ImageGray<T>> T convertFromSingle(BufferedImage src, T dst, Class<T> type) {
		if (type == GrayU8.class) {
			return (T) convertFrom(src, (GrayU8) dst);
		} else if( GrayI16.class.isAssignableFrom(type) ) {
			return (T) convertFrom(src, (GrayI16) dst,(Class)type);
		} else if (type == GrayF32.class) {
			return (T) convertFrom(src, (GrayF32) dst);
		} else {
			throw new IllegalArgumentException("Unknown type " + type);
		}
	}
86842
def palettize(self, colormap):
        

        if self.mode not in ("L", "LA"):
            raise ValueError("Image should be grayscale to colorize")
        self.channels[0], self.palette = colormap.palettize(self.channels[0])
        if self.mode == "L":
            self.mode = "P"
        else:
            self.mode = "PA"
970838
def do_quality(self, quality):
        
        if (quality == 'grey' or quality == 'gray'):
            # Checking for 1.1 gray or 20.0 grey elsewhere
            self.logger.debug("quality: converting to gray")
            self.image = self.image.convert('L')
        elif (quality == 'bitonal'):
            self.logger.debug("quality: converting to bitonal")
            self.image = self.image.convert('1')
        else:  # color or default/native (which we take as color)
            # Deal first with conversions from I;16* formats which Pillow
            # appears not to handle properly, resulting in mostly white images
            # if we convert directly. See:
            # <http://stackoverflow.com/questions/7247371/python-and-16-bit-tiff>
            if (self.image.mode.startswith('I;16')):
                self.logger.debug("quality: fudged conversion from mode %s to I"
                                  % (self.image.mode))
                self.image = self.image.convert('I')
                self.image = self.image.point(lambda i: i * (1.0 / 256.0))
            if (self.image.mode not in ('1', 'L', 'RGB', 'RGBA')):
                # Need to convert from palette etc. in order to write out
                self.logger.debug("quality: converting from mode %s to RGB"
                                  % (self.image.mode))
                self.image = self.image.convert('RGB')
            else:
                self.logger.debug("quality: quality (nop)")
830941
public static void pixelAccess(  BufferedImage input ) {
		// convert the BufferedImage into a Planar
		Planar<GrayU8> image = ConvertBufferedImage.convertFromPlanar(input,null,true,GrayU8.class);

		int x = 10, y = 10;

		// to access a pixel you first access the gray image for the each band
		for( int i = 0; i < image.getNumBands(); i++ )
			System.out.println("Original "+i+" = "+image.getBand(i).get(x,y));

		// change the value in each band
		for( int i = 0; i < image.getNumBands(); i++ )
			image.getBand(i).set(x, y, 100 + i);

		// to access a pixel you first access the gray image for the each band
		for( int i = 0; i < image.getNumBands(); i++ )
			System.out.println("Result   "+i+" = "+image.getBand(i).get(x,y));
	}

	/**
	 * There is no real perfect way that everyone agrees on for converting color images into gray scale
	 * images.  Two examples of how to convert a Planar image into a gray scale image are shown
	 * in this example.
	 */
	public static void convertToGray( BufferedImage input ) {
		// convert the BufferedImage into a Planar
		Planar<GrayU8> image = ConvertBufferedImage.convertFromPlanar(input,null,true,GrayU8.class);

		GrayU8 gray = new GrayU8( image.width,image.height);

		// creates a gray scale image by averaging intensity value across pixels
		ConvertImage.average(image, gray);
		BufferedImage outputAve = ConvertBufferedImage.convertTo(gray,null);

		// convert to gray scale but weigh each color band based on how human vision works
		ColorRgb.rgbToGray_Weighted(image, gray);
		BufferedImage outputWeighted = ConvertBufferedImage.convertTo(gray,null);

		// create an output image just from the first band
		BufferedImage outputBand0 = ConvertBufferedImage.convertTo(image.getBand(0),null);

		gui.addImage(outputAve,"Gray Averaged");
		gui.addImage(outputWeighted,"Gray Weighted");
		gui.addImage(outputBand0,"Band 0");
	}
	
	public static void main( String args[] ) {
		BufferedImage input = UtilImageIO.loadImage(UtilIO.pathExample("apartment_building_02.jpg"));

		// Uncomment lines below to run each example

		ExamplePlanarImages.independent(input);
		ExamplePlanarImages.pixelAccess(input);
		ExamplePlanarImages.convertToGray(input);

		ShowImages.showWindow(gui,"Color Planar Image Examples",true);
	}
}
807655
public static void grayToBitmap( ImageGray input , Bitmap output , byte[] storage) {
		if( input instanceof GrayU8 )
			grayToBitmap((GrayU8)input,output,storage);
		else if( input instanceof GrayF32 )
			grayToBitmap((GrayF32)input,output,storage);
		else
			throw new IllegalArgumentException("Unsupported BoofCV Type: "+input);
	}
1007271
def _convert(self, image, output=None):
        """"""
        with Image.open(image) as im:
            width, height = im.size

            co = CanvasObjects()
            co.add(CanvasImg(image, 1.0, w=width, h=height))

            return WatermarkDraw(co, tempdir=self.tempdir, pagesize=(width, height)).write(output)
948964
public static void scaleImageUp(GrayU8 input , GrayU8 output , int scale ,
									InterpolatePixelS<GrayU8> interp ) {
		output.reshape(input.width*scale,input.height*scale);

		float fdiv = 1/(float)scale;
		interp.setImage(input);

		for (int y = 0; y < output.height; y++) {
			float inputY = y*fdiv;
			int indexOutput = output.getIndex(0,y);

			for (int x = 0; x < output.width; x++) {
				float inputX = x*fdiv;

				output.data[indexOutput++] = (byte)interp.get(inputX,inputY);
			}
		}
	}
70553
@Override
	public void denoise(GrayF32 transform , int numLevels ) {
		int scale = UtilWavelet.computeScale(numLevels);

		final int h = transform.height;
		final int w = transform.width;

		// width and height of scaling image
		final int innerWidth = w/scale;
		final int innerHeight = h/scale;

		GrayF32 subbandHH = transform.subimage(w/2,h/2,w,h, null);
		float sigma = UtilDenoiseWavelet.estimateNoiseStdDev(subbandHH,null);
		float threshold = (float) UtilDenoiseWavelet.universalThreshold(subbandHH,sigma);

		// apply same threshold to all wavelet coefficients
		rule.process(transform.subimage(innerWidth,0,w,h, null),threshold);
		rule.process(transform.subimage(0,innerHeight,innerWidth,h, null),threshold);
	}
1255885
def imageToColor(url: str, scale=200, mode='rgb'):
        """"""
        from PIL import Image
        import colorsys
        if url:
            response = urllib.request.urlopen(url)
            img_buffer = io.BytesIO(response.read())
            img = Image.open(img_buffer)
            img = img.convert('RGBA')
            img.thumbnail((scale, scale))
            statistics = {'r': 0, 'g': 0, 'b': 0, 'coef': 0}
            for cnt, (r, g, b, a) in img.getcolors(img.size[0] * img.size[1]):
                hsv = colorsys.rgb_to_hsv(r / 255, g / 255, b / 255)
                saturation = hsv[1] * 255
                coefficient = (saturation * cnt * a) + 0.01  # avoid 0
                statistics['r'] += coefficient * r
                statistics['g'] += coefficient * g
                statistics['b'] += coefficient * b
                statistics['coef'] += coefficient
                color = (
                    int(statistics['r'] / statistics['coef']),
                    int(statistics['g'] / statistics['coef']),
                    int(statistics['b'] / statistics['coef'])
                )
            if mode.lower() == 'rgb':
                return color
            elif mode.lower() == 'hex':
                return "#%0.2X%0.2X%0.2X" % color
            else:
                return color
        else:
            return False
472169
public static void convertToBoof(Picture input, ImageBase output) {
		if( input.getColor() == ColorSpace.RGB ) {
			ImplConvertJCodecPicture.RGB_to_PLU8(input, (Planar) output);
		} else if( input.getColor() == ColorSpace.YUV420 ) {
			if( output instanceof Planar) {
				Planar ms = (Planar)output;
				if( ms.getImageType().getDataType() == ImageDataType.U8 ) {
					ImplConvertJCodecPicture.yuv420_to_PlRgb_U8(input, ms);
				} else if( ms.getImageType().getDataType() == ImageDataType.F32 ) {
					ImplConvertJCodecPicture.yuv420_to_PlRgb_F32(input, ms);
				}
			} else if( output instanceof GrayU8) {
				ImplConvertJCodecPicture.yuv420_to_U8(input, (GrayU8) output);
			} else if( output instanceof GrayF32) {
				ImplConvertJCodecPicture.yuv420_to_F32(input, (GrayF32) output);
			} else {
				throw new RuntimeException("Unexpected output image type");
			}
		}
	}
861834
def _remove_white_background(image):
    """"""
    from PIL import ImageMath, Image
    if image.mode == "RGBA":
        bands = image.split()
        a = bands[3]
        rgb = [
            ImageMath.eval(
                'convert('
                'float(x + a - 255) * 255.0 / float(max(a, 1)) * '
                'float(min(a, 1)) + float(x) * float(1 - min(a, 1))'
                ', "L")',
                x=x, a=a
            )
            for x in bands[:3]
        ]
        return Image.merge(bands=rgb + [a], mode="RGBA")

    return image
952250
def try_greyscale(pixels, alpha=False, dirty_alpha=True):
    
    planes = 3 + bool(alpha)
    res = list()
    apix = list()
    for row in pixels:
        green = row[1::planes]
        if alpha:
            apix.append(row[4:planes])
        if (green != row[0::planes] or green != row[2::planes]):
            return False
        else:
            res.append(green)
    if alpha:
        return MergedPlanes(res, 1, apix, 1)
    else:
        return res
867386
def rgb2cmy(self, img, whitebg=False):
        """"""
        tmp = img*1.0
        if whitebg:
            tmp = (1.0 - (img - img.min())/(img.max() - img.min()))
        out = tmp*0.0
        out[:,:,0] = (tmp[:,:,1] + tmp[:,:,2])/2.0
        out[:,:,1] = (tmp[:,:,0] + tmp[:,:,2])/2.0
        out[:,:,2] = (tmp[:,:,0] + tmp[:,:,1])/2.0
        return out